package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.plan.domain.DimShift;
import net.hn.hnms.biz.plan.domain.DispatchKeepWatch;
import net.hn.hnms.biz.plan.domain.DispatchKeepWatchPerson;
import net.hn.hnms.biz.plan.enums.KeepWatchPersonType;
import net.hn.hnms.biz.plan.enums.PostTypeEnum;
import net.hn.hnms.biz.plan.enums.ShiftTypeEnum;
import net.hn.hnms.biz.plan.mapper.DimShiftMapper;
import net.hn.hnms.biz.plan.mapper.DispatchKeepWatchMapper;
import net.hn.hnms.biz.plan.mapper.DispatchKeepWatchPersonMapper;
import net.hn.hnms.biz.plan.request.DispatchKeepWatchDutyReq;
import net.hn.hnms.biz.plan.request.DispatchKeepWatchLeadReq;
import net.hn.hnms.biz.plan.request.DispatchKeepWatchReq;
import net.hn.hnms.biz.plan.request.UpdateDutyLDReq;
import net.hn.hnms.biz.plan.service.IDispatchKeepWatchService;
import net.hn.hnms.biz.plan.vo.DispatchKeepWatchPersonVO;
import net.hn.hnms.biz.plan.vo.DispatchKeepWatchVO;
import net.hn.hnms.biz.plan.vo.RankScore;
import net.hn.hnms.biz.plan.vo.work.*;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.DateUtils;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.excel.core.ExcelResult;
import net.hn.hnms.sys.common.excel.utils.ExcelUtil;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.common.redis.utils.RedisUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.IsoFields;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.apache.poi.ss.usermodel.BorderStyle.THIN;
import static org.apache.poi.ss.usermodel.HorizontalAlignment.CENTER;

/**
 * @author zhaoyang
 * 带值班管理服务层实现
 * @date 2022-08-01
 */

@Service
@Slf4j
@DS("master")
public class DispatchKeepWatchServiceImpl extends BaseService<DispatchKeepWatch, DispatchKeepWatchVO> implements IDispatchKeepWatchService {

    private final static String cacheKey = "dispatch-result-dict";

    @Autowired
    private DispatchKeepWatchMapper dispatchKeepWatchMapper;

    @Autowired
    private DimShiftMapper dimShiftMapper;

    @Autowired
    private DispatchKeepWatchPersonMapper dispatchKeepWatchPersonMapper;

    /**
     * @param dispatchKeepWatch
     * @param pageQuery         查询带值班列表
     */
    @Override
    public ResponsePage<DispatchKeepWatchVO> selectPageList(DispatchKeepWatchReq dispatchKeepWatch, PageQuery pageQuery) {

        Page<DispatchKeepWatchVO> page = dispatchKeepWatchMapper.selectPageList(pageQuery.build(), dispatchKeepWatch);

        if (CollUtil.isNotEmpty(page.getRecords())) {
            Set<String> shiftIds = page.getRecords().stream().map(DispatchKeepWatchVO::getShiftId).collect(Collectors.toSet());
            DynamicDataSourceContextHolder.push("slave");
            Map<String, String> shiftMap = dimShiftMapper.selectList(new LambdaQueryWrapper<DimShift>().in(CollUtil.isNotEmpty(shiftIds), DimShift::getShiftId, shiftIds))
                    .stream().collect(Collectors.toMap(DimShift::getShiftId, DimShift::getShiftName));
            DynamicDataSourceContextHolder.clear();
            for (DispatchKeepWatchVO watchVO : page.getRecords()) {
                watchVO.setStatus(StrUtil.isBlank(watchVO.getLeadPersonIds()) ? "0" : watchVO.getStatus());
                watchVO.setShiftName(shiftMap.get(watchVO.getShiftId()));
            }
        }
        return new ResponsePage<>(page.getRecords(), page.getTotal());
    }

    /**
     * 构造查询条件
     *
     * @param req
     * @return LambdaQueryWrapper<DispatchKeepWatch> 查询条件
     */
    private LambdaQueryWrapper<DispatchKeepWatch> buildQuery(DispatchKeepWatchReq req) {
        LambdaQueryWrapper<DispatchKeepWatch> lqw = new LambdaQueryWrapper<DispatchKeepWatch>()
                .eq(StrUtil.isNotBlank(req.getStatus()), DispatchKeepWatch::getStatus, req.getStatus())
                .eq(StrUtil.isNotBlank(req.getShiftId()), DispatchKeepWatch::getShiftId, req.getShiftId())
                .ge(req.getBeginDateTime() != null, DispatchKeepWatch::getKeepWatchDate, req.getBeginDateTime())
                .le(req.getEndDateTime() != null, DispatchKeepWatch::getKeepWatchDate, req.getEndDateTime());

        //人员名称查询
        if (StrUtil.isNotBlank(req.getPersonName())) {
            List<DispatchKeepWatchPerson> personList = dispatchKeepWatchPersonMapper.selectList(
                    new LambdaQueryWrapper<DispatchKeepWatchPerson>().like(DispatchKeepWatchPerson::getKeepWatchPersonName, req.getPersonName())
            );
            LambdaQueryWrapper<DispatchKeepWatch> lqw2 = new LambdaQueryWrapper<>();
            for (DispatchKeepWatchPerson dispatchKeepWatchPerson : personList) {
                lqw2.or(o -> o.like(DispatchKeepWatch::getLeadPersonIds, dispatchKeepWatchPerson.getKeepWatchPersonId()));
                lqw2.or(o -> o.like(DispatchKeepWatch::getDutyPersonIds, dispatchKeepWatchPerson.getKeepWatchPersonId()));
            }
            List<DispatchKeepWatch> watchList = dispatchKeepWatchMapper.selectList(lqw2);
            lqw.in(CollUtil.isNotEmpty(watchList), DispatchKeepWatch::getKeepWatchId,
                    watchList.parallelStream().map(DispatchKeepWatch::getKeepWatchId).collect(Collectors.toList()));
        }
        lqw.orderByDesc(DispatchKeepWatch::getKeepWatchDate);
        return lqw;
    }

    /**
     * @param dispatchKeepWatch 查询带值班人员列表
     */
    @Override
    public List<DispatchKeepWatchVO> selectList(DispatchKeepWatchReq dispatchKeepWatch) {
        List<DispatchKeepWatch> list = dispatchKeepWatchMapper.selectList(buildQuery(dispatchKeepWatch));
        return list.stream().map(o -> convert(o, DispatchKeepWatchVO.class)).collect(Collectors.toList());
    }

    /**
     * 新增带班
     *
     * @param leadReq
     * @return 1 or 0
     */
    @Override
    public int insertLead(DispatchKeepWatchLeadReq leadReq) {
        if (StrUtil.isBlank(leadReq.getLeadPersonIds())) {
            throw new HuaNengException(Constants.FAIL, "请选择带班人员");
        }
        if (StrUtil.isBlank(leadReq.getShiftId())) {
            throw new HuaNengException(Constants.FAIL, "请选择班次");
        }
        //判断是否有值班
        String[] result = leadReq.getLeadPersonIds().split(",");
        for (String r : result) {
            QueryWrapper<DispatchKeepWatch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("keep_watch_date", leadReq.getKeepWatchDate());
//        queryWrapper.eq("shift_id", dispatchKeepWatch.getShiftId());
            queryWrapper.eq("type", "1");
            queryWrapper.eq("duty_person_ids", r);
            QueryWrapper<DispatchKeepWatch> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("keep_watch_date", leadReq.getKeepWatchDate());
            queryWrapper.eq("shift_id", leadReq.getShiftId());
            queryWrapper1.eq("type", "2");
            queryWrapper1.eq("lead_person_ids", r);

            if (dispatchKeepWatchMapper.selectCount(queryWrapper) > 0) {
                throw new HuaNengException(Constants.FAIL, "与值班冲突,请调整值班!");
            }
            if (dispatchKeepWatchMapper.selectCount(queryWrapper1) > 0) {
                throw new HuaNengException(Constants.FAIL, "该班次该人员已存在");
            }

            //删除目标日得带班,新增某个班次得带班
//            dispatchKeepWatchMapper.deleteByDate(DateUtil.formatDate(leadReq.getKeepWatchDate()),leadReq.getShiftId());
            DispatchKeepWatch dw = new DispatchKeepWatch();
            dw.setLeadPersonIds(r);
            dw.setType("2");
            dw.setDelFlag("0");
            dw.setStatus("0");
            dw.setMineCode(leadReq.getMineCode());
            dw.setShiftId(leadReq.getShiftId());
            dw.setKeepWatchDate(leadReq.getKeepWatchDate());
//            dw.setLeadPersonIds(r);
            dispatchKeepWatchMapper.insert(dw);
        }

        return 0;
    }

    @Override
    public int insertLeadLD(DispatchKeepWatchLeadReq leadReq) {
        if (StrUtil.isBlank(leadReq.getLeadPersonIds())) {
            throw new HuaNengException(Constants.FAIL, "请选择带班人员");
        }
        if (StrUtil.isBlank(leadReq.getShiftId())) {
            throw new HuaNengException(Constants.FAIL, "请选择班次");
        }
        String[] result = leadReq.getLeadPersonIds().split(",");
        for (String r : result) {


            //删除目标日得带班,新增某个班次得带班
//            dispatchKeepWatchMapper.deleteByDate(DateUtil.formatDate(leadReq.getKeepWatchDate()),leadReq.getShiftId());
            DispatchKeepWatch dw = new DispatchKeepWatch();
            dw.setLeadPersonIds(r);
            dw.setType("2");
            dw.setDelFlag("0");
            dw.setStatus("0");
            dw.setMineCode(leadReq.getMineCode());
            dw.setShiftId(leadReq.getShiftId());
            dw.setKeepWatchDate(leadReq.getKeepWatchDate());
//            dw.setLeadPersonIds(r);
            dispatchKeepWatchMapper.insert(dw);
        }

        return 0;
    }


    /**
     * 新增值班
     *
     * @param dutyReq
     * @return 1 or 0
     */
    @Override
    public int insertDuty(DispatchKeepWatchDutyReq dutyReq) {
        if (StrUtil.isBlank(dutyReq.getDutyPersonIds())) {
            throw new HuaNengException(Constants.FAIL, "请选择值班人员");
        }
        //数据校验判断是否有带班
        QueryWrapper<DispatchKeepWatch> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("keep_watch_date", dutyReq.getKeepWatchDate());
        queryWrapper.eq("lead_person_ids", dutyReq.getDutyPersonIds());
        QueryWrapper<DispatchKeepWatch> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("keep_watch_date", dutyReq.getKeepWatchDate());
        queryWrapper1.eq("duty_person_ids", dutyReq.getDutyPersonIds());
        if (dispatchKeepWatchMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "与带班冲突,请调整带班!");
        }
        if (dispatchKeepWatchMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "数据已存在");
        }
        DispatchKeepWatch insertObj = new DispatchKeepWatch();
        BeanUtil.copyProperties(dutyReq, insertObj);
        insertObj.setLeadPersonIds("");
        insertObj.setStatus("0");
        insertObj.setType("1");
        return dispatchKeepWatchMapper.insert(insertObj);
    }

    @Override
    public int insertDutyLD(UpdateDutyLDReq dutyReq) {


        if (dutyReq.getDutyPersonIds() == null) {
            throw new HuaNengException(Constants.FAIL, "请选择值班人员");
        }
        int i = 0;
        for (String dutyPersonId : dutyReq.getDutyPersonIds()) {
            // 处理每个dutyPersonId
            System.out.println(dutyPersonId);
            //新增
            DispatchKeepWatch duty = new DispatchKeepWatch();
            try {
                duty.setKeepWatchDate(DateUtils.parseDate(dutyReq.getKeepWatchDate(), "yyyy-MM-dd"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            duty.setDutyPersonIds(dutyPersonId);
            duty.setLeadPersonIds("");
            duty.setStatus("0");
            duty.setType("1");
            duty.setMineCode(dutyReq.getMineCode());
            duty.setDelFlag("0");
            i += dispatchKeepWatchMapper.insert(duty);

        }
        return i;
    }

    /**
     * @param idList 批量删除 id集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        dispatchKeepWatchMapper.deleteBatchIds(idList);
    }

    /**
     * @param dispatchKeepWatch 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(DispatchKeepWatchReq dispatchKeepWatch) {
        if (StrUtil.isBlank(dispatchKeepWatch.getKeepWatchId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        if (!DateUtil.isSameDay(dispatchKeepWatch.getKeepWatchDate(), dispatchKeepWatch.getKeepWatchOldDate())) {
            //数据校验
            QueryWrapper<DispatchKeepWatch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("keep_watch_date", dispatchKeepWatch.getKeepWatchDate());
            queryWrapper.eq("shift_id", dispatchKeepWatch.getShiftId());
            queryWrapper.eq("duty_person_ids", "");
            if (dispatchKeepWatchMapper.selectCount(queryWrapper) > 0) {
                throw new HuaNengException(Constants.FAIL, "您选择的值班日期和班次已经设置过带班人员了");
            }
        }

        //修改值班
        DispatchKeepWatch duty = dispatchKeepWatchMapper.selectOne(new LambdaQueryWrapper<DispatchKeepWatch>()
                .eq(DispatchKeepWatch::getKeepWatchDate, dispatchKeepWatch.getKeepWatchOldDate()).eq(DispatchKeepWatch::getLeadPersonIds, ""));

        //判断是否是值班
        boolean isUpdateDuty = duty != null && duty.getKeepWatchId().equals(dispatchKeepWatch.getKeepWatchId());
        if (duty != null) {
            duty.setKeepWatchDate(dispatchKeepWatch.getKeepWatchDate());
            duty.setDutyPersonIds(dispatchKeepWatch.getDutyPersonIds());
            duty.setLeadPersonIds("");
            dispatchKeepWatchMapper.updateById(duty);
        } else {
            duty = new DispatchKeepWatch();
            duty.setKeepWatchDate(dispatchKeepWatch.getKeepWatchDate());
            duty.setDutyPersonIds(dispatchKeepWatch.getDutyPersonIds());
            duty.setLeadPersonIds("");
            duty.setStatus("0");
            dispatchKeepWatchMapper.insert(duty);
        }
        //修改带班
        if (isUpdateDuty) {
            //如果当前是修改值班
            //新增带班
            DispatchKeepWatch updateObj = new DispatchKeepWatch();
            updateObj.setKeepWatchDate(dispatchKeepWatch.getKeepWatchDate());
            updateObj.setLeadPersonIds(dispatchKeepWatch.getLeadPersonIds());
            updateObj.setDutyPersonIds("");
            updateObj.setShiftId(dispatchKeepWatch.getShiftId());
            updateObj.setStatus("0");
            dispatchKeepWatchMapper.insert(updateObj);
        } else {
            DispatchKeepWatch updateObj = dispatchKeepWatchMapper.selectById(dispatchKeepWatch.getKeepWatchId());
            if (updateObj == null) {
                if (StrUtil.isNotBlank(dispatchKeepWatch.getKeepWatchId())) {
                    throw new HuaNengException(Constants.FAIL, "数据不存在");
                } else {
                    //新增带班
                    updateObj = new DispatchKeepWatch();
                    updateObj.setKeepWatchDate(dispatchKeepWatch.getKeepWatchDate());
                    updateObj.setLeadPersonIds(dispatchKeepWatch.getLeadPersonIds());
                    updateObj.setDutyPersonIds("");
                    updateObj.setShiftId(dispatchKeepWatch.getShiftId());
                    updateObj.setStatus("0");
                    dispatchKeepWatchMapper.insert(updateObj);
                }
            } else {
                updateObj.setKeepWatchDate(dispatchKeepWatch.getKeepWatchDate());
                updateObj.setLeadPersonIds(dispatchKeepWatch.getLeadPersonIds());
                updateObj.setShiftId(dispatchKeepWatch.getShiftId());
                updateObj.setDutyPersonIds("");
                dispatchKeepWatchMapper.updateById(updateObj);
            }
        }

    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public DispatchKeepWatchVO selectDetailById(String id) {
        DispatchKeepWatch dispatchKeepWatch = dispatchKeepWatchMapper.selectById(id);
        if (dispatchKeepWatch == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(dispatchKeepWatch, DispatchKeepWatchVO.class);
    }


    /**
     * 启用/禁用
     */
    public void changeStatus(DispatchKeepWatchReq dispatchKeepWatch) {

        if (StrUtil.equals(dispatchKeepWatch.getStatus(), "1") || StrUtil.equals(dispatchKeepWatch.getStatus(), "0")) {
            DispatchKeepWatch watch = dispatchKeepWatchMapper.selectById(dispatchKeepWatch.getKeepWatchId());
            if (watch != null) {
                if (StrUtil.isBlank(watch.getLeadPersonIds())) {
                    throw new HuaNengException(Constants.FAIL, "值班信息状态不能修改");
                }
                watch.setStatus(dispatchKeepWatch.getStatus());
                int res = dispatchKeepWatchMapper.updateById(watch);
                if (res == 0) {
                    throw new HuaNengException(Constants.FAIL, "数据不存在");
                }
                return;
            } else {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }


    /**
     * 获取当天值班人员
     *
     * @return PlanApplication
     */
    @Override
    public List<DispatchKeepWatchPerson> getPersonByToday() {
        Date now = new Date();
        DispatchKeepWatch keepWatch = dispatchKeepWatchMapper.selectOne(new LambdaQueryWrapper<DispatchKeepWatch>()
                .apply(" keep_watch_date = to_date('" + DateUtil.formatDate(now) + "','YYYY-MM-DD') ")
                .eq(DispatchKeepWatch::getStatus, "0")
                .last("and lead_person_ids='' limit 1")
        );
        if (keepWatch != null) {
            String[] personIds = keepWatch.getDutyPersonIds().split(",");
            if (personIds.length > 0) {
                return dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                        .in(DispatchKeepWatchPerson::getKeepWatchPersonId, personIds)
                        .eq(DispatchKeepWatchPerson::getStatus, "0"));
            }
        }
        return ListUtil.empty();
    }


    /**
     * 自动排班
     *
     * @param beginDate 时间范围
     * @param endDate   时间范围
     * @param number    人数
     * @return List<DispatchKeepWatchVO> 排班信息
     */
    @Override
    public List<DispatchKeepWatchVO> automatic(Date beginDate, Date endDate, Integer number) {
        if (beginDate == null || endDate == null) {
            throw new HuaNengException(Constants.FAIL, "请选择时间范围");
        }
        if (number == null) {
            throw new HuaNengException(Constants.FAIL, "请输入班次人数");
        }
        if (number < 0) {
            throw new HuaNengException(Constants.FAIL, "班次人数输入错误");
        }
        if (endDate.before(beginDate)) {
            throw new HuaNengException(Constants.FAIL, "开始日期不能在结束日期之前");
        }
        DynamicDataSourceContextHolder.push("slave");
        List<DimShift> shiftList = dimShiftMapper.selectList(new LambdaQueryWrapper<DimShift>()
                .eq(DimShift::getStatus, "0").orderByAsc(DimShift::getShiftStartTime));
        DynamicDataSourceContextHolder.clear();
        if (CollUtil.isEmpty(shiftList)) {
            throw new HuaNengException(Constants.FAIL, "班次信息不存在");
        }

        long between = DateUtil.between(beginDate, endDate, DateUnit.DAY, true) + 1;
        List<DispatchKeepWatchPerson> personList = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0"));
        if (CollUtil.isEmpty(personList)) {
            throw new HuaNengException(Constants.FAIL, "未设置值班人员和带班人员");
        }
        if ((number + 1) > (personList.stream().map(DispatchKeepWatchPerson::getKeepWatchPersonName).distinct().count())) {
            throw new HuaNengException(Constants.FAIL, "已有的值班人员和带班人员不能满足班次人员个数配置");
        }
        //值班人员
        LinkedList<DispatchKeepWatchPerson> dutyList = new LinkedList<>();
        //得分与优先级list
        List<RankScore> rankList = new ArrayList<>();
        //带班人员
        LinkedList<DispatchKeepWatchPerson> leadList = new LinkedList<>();
        for (DispatchKeepWatchPerson person : personList) {
            //起始默认优先级0
            if (StrUtil.equals(person.getKeepWatchPersonType(), KeepWatchPersonType.DUTY.getCode())) {
                dutyList.add(person);
            } else if (StrUtil.equals(person.getKeepWatchPersonType(), KeepWatchPersonType.LEAD.getCode())) {
                rankList.add(new RankScore(person.getKeepWatchPersonId(), 0, 0));
                leadList.add(person);
            } else {
                rankList.add(new RankScore(person.getKeepWatchPersonId(), 0, 0));
                dutyList.add(person);
                leadList.add(person);
            }
        }
        if (CollUtil.isEmpty(dutyList)) {
            throw new HuaNengException(Constants.FAIL, "未设置值班人员");
        }
        if (CollUtil.isEmpty(leadList)) {
            throw new HuaNengException(Constants.FAIL, "未设置带班人员");
        }
        List<DispatchKeepWatchVO> dutyResult = new ArrayList<>();
        for (int i = 0; i < between; i++) {
            //先排值班人员
            DispatchKeepWatchVO watchVO = new DispatchKeepWatchVO();
            watchVO.setKeepWatchDate(DateUtil.offsetDay(beginDate, i));
            DispatchKeepWatchPerson dutyPerson = dutyList.get(0);
            watchVO.setDutyPersonIds(dutyPerson.getKeepWatchPersonId());
            watchVO.setDutyPersonNames(dutyPerson.getKeepWatchPersonName());
            dutyResult.add(watchVO);
            //被选择一次 优先级就加1
            if (dutyPerson.getKeepWatchPersonType().equals("3")) {
                addScoreAndPriority(rankList, dutyPerson.getKeepWatchPersonId(), 1, 0);
            }
            //删除头部 追加到尾部
            dutyList.add(dutyPerson);
            dutyList.remove(0);

        }
        List<DispatchKeepWatchVO> result = new ArrayList<>();
        //升序 TreeSet
        List<RankScore> oldLeadPersons;
        Set<String> oldLeadPersonsIds = new HashSet<>();
        String lastDutyPersonId = "";
        for (int i = 0; i < dutyResult.size(); i++) {
            DispatchKeepWatchVO dutyVO = dutyResult.get(i);
            if (i > 0) {
                lastDutyPersonId = dutyResult.get(i - 1).getDutyPersonIds();
            }
            for (DimShift dimShift : shiftList) {
                DispatchKeepWatchVO watchVO = new DispatchKeepWatchVO();
                watchVO.setKeepWatchDate(dutyVO.getKeepWatchDate());
                watchVO.setShiftName(dimShift.getShiftName());
                watchVO.setShiftId(dimShift.getShiftId());

                Set<String> finalOldLeadPersonsIds = oldLeadPersonsIds;
                oldLeadPersons = rankList.stream().filter(o -> finalOldLeadPersonsIds.contains(o.getKey())).collect(Collectors.toList());
                oldLeadPersons.removeIf(o -> o.getKey().equals(dutyVO.getDutyPersonIds()));

                //筛选出 number个带班人员
                List<DispatchKeepWatchPerson> leadPersons = randomLeadPersons(rankList, leadList, oldLeadPersons, lastDutyPersonId, dutyVO.getDutyPersonIds(), number);
                oldLeadPersonsIds.clear();
                oldLeadPersonsIds = leadPersons.stream().map(DispatchKeepWatchPerson::getKeepWatchPersonId).collect(Collectors.toSet());
                watchVO.setLeadPersonIds(leadPersons.stream().map(DispatchKeepWatchPerson::getKeepWatchPersonId).collect(Collectors.joining(",")));
                watchVO.setLeadPersonNames(leadPersons.stream().map(DispatchKeepWatchPerson::getKeepWatchPersonName).collect(Collectors.joining(",")));

                watchVO.setDutyPersonIds(dutyVO.getDutyPersonIds());
                watchVO.setDutyPersonNames(dutyVO.getDutyPersonNames());

                result.add(watchVO);
            }
        }

        return result;
    }


    @Override
    public List<DispatchKeepWatchVO> automaticHTY(Date beginDate, String mineCode) {
        List<DispatchKeepWatchVO> result = Lists.newArrayList();
        //根据月份获取当月的天数
        int days = getDaysOfMonth(beginDate);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String nianYue = new SimpleDateFormat("yyyy-MM").format(DateUtils.dateTime("yyyy-MM-dd", dateFormat.format(beginDate)));
        int countMatic = dispatchKeepWatchMapper.countMatic(nianYue);
        if (countMatic >= days) {
            throw new HuaNengException(Constants.FAIL, nianYue + "月,已存在班次信息");
        }
        // 获取带值班人员
        List<DispatchKeepWatchPerson> dispatchKeepWatchPeople = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>().eq(DispatchKeepWatchPerson::getDelFlag, "0"));
        if (CollectionUtils.isNotEmpty(dispatchKeepWatchPeople)) {
            List<ScheduleEntryVo> scheduleEntries = new ArrayList<>();
            // 矿长和党委书记
            List<LeaderShiftVo> leaders = dispatchKeepWatchPeople.stream().filter(u -> !StringUtils.equals(PostTypeEnum.FZGCS.getCode(), u.getPostType()))
                    .map(u -> new LeaderShiftVo(u.getKeepWatchPersonId(), u.getKeepWatchPersonName(), u.getPostType(), PostTypeEnum.getMinShifts(u.getPostType()), PostTypeEnum.getMaxShifts(u.getPostType()))).collect(Collectors.toList());
            // 副总工程师
            List<LeaderShiftVo> viceEngineers = dispatchKeepWatchPeople.stream().filter(u -> StringUtils.equals(PostTypeEnum.FZGCS.getCode(), u.getPostType()))
                    .map(l -> new ViceEngineerShiftVo(l.getKeepWatchPersonId(), l.getKeepWatchPersonName(), PostTypeEnum.getMinShifts(l.getPostType()), PostTypeEnum.getMaxShifts(l.getPostType()))).collect(Collectors.toList());
            // 分配周末轮休批次，包括所有领导成员
            List<LeaderShiftVo> weekendBatchOne = new ArrayList<>(); // 第一批周末轮休
            List<LeaderShiftVo> weekendBatchTwo = new ArrayList<>(); // 第二批周末轮休
            List<LeaderShiftVo> remainingLeaders = leaders.stream()
                    .filter(l -> !l.getPostType().equals(PostTypeEnum.KZ.getCode()) && !l.getPostType().equals(PostTypeEnum.DWSJ.getCode()))
                    .collect(Collectors.toList());
            weekendBatchOne.add(leaders.stream().filter(l -> l.getPostType().equals(PostTypeEnum.KZ.getCode())).findFirst().get());
            weekendBatchTwo.add(leaders.stream().filter(l -> l.getPostType().equals(PostTypeEnum.DWSJ.getCode())).findFirst().get());
            for (int i = 0; i < remainingLeaders.size(); i++) {
                if (i % 2 == 0) {
                    weekendBatchOne.add(remainingLeaders.get(i));
                } else {
                    weekendBatchTwo.add(remainingLeaders.get(i));
                }
            }
            for (int i = 0; i < viceEngineers.size(); i++) {
                if (i % 2 == 0) {
                    weekendBatchOne.add(viceEngineers.get(i));
                } else {
                    weekendBatchTwo.add(viceEngineers.get(i));
                }
            }
            leaders.addAll(viceEngineers);
            LocalDate startDate = beginDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate endDate = startDate.plusMonths(1).plusDays(-1); // 排班周期为一个月

            while (!startDate.isAfter(endDate)) {
                System.out.println("Processing date: " + startDate);
                if (startDate.getDayOfWeek().getValue() > 5) { // 如果是周末
                    assignWeekendShifts(startDate, scheduleEntries, weekendBatchOne, weekendBatchTwo);
                } else {
                    assignDayShifts(startDate, leaders, viceEngineers, scheduleEntries);
                }
                startDate = startDate.plusDays(1);
            }
            Map<String, String> shiftMap = new HashMap<>();
            for (ShiftTypeEnum value : ShiftTypeEnum.values()) {
                shiftMap.put(value.getName(), getShiftList(value.getName()));
            }
            List<DispatchKeepWatch> dispatchKeepWatchList = new ArrayList<>();
            scheduleEntries.forEach(item -> {
                DispatchKeepWatch dispatchKeepWatch = new DispatchKeepWatch();
                dispatchKeepWatch.setKeepWatchDate(Date.from(item.getDate().atStartOfDay(ZoneId.systemDefault()).toInstant()));
                dispatchKeepWatch.setType(item.getDutyType());
                if (StringUtils.equals(item.getDutyType(), "1")) {
                    dispatchKeepWatch.setDutyPersonIds(item.getPerson().getId());
                } else {
                    dispatchKeepWatch.setLeadPersonIds(item.getPerson().getId());
                }
                dispatchKeepWatch.setShiftId(shiftMap.get(item.getShiftType()));
                dispatchKeepWatch.setDelFlag("0");
                dispatchKeepWatchList.add(dispatchKeepWatch);
            });
            if (CollectionUtils.isNotEmpty(dispatchKeepWatchList)) {
                dispatchKeepWatchMapper.insertBatch(dispatchKeepWatchList);
            }
        }
        return result;
    }

    private static void assignWeekendShifts(LocalDate date, List<ScheduleEntryVo> schedule, List<LeaderShiftVo> weekendBatchOne, List<LeaderShiftVo> weekendBatchTwo) {
        // 根据当前日期选择合适的批次
        int weekNumber = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
        List<LeaderShiftVo> currentBatch = (weekNumber % 2 == 0) ? weekendBatchTwo : weekendBatchOne;
        // 分配值班领导
        LeaderShiftVo onDutyLeader = selectOnDutyLeader(date, currentBatch, true);
        onDutyLeader.assignShift(new ShiftVo(null, date, "1"));
        schedule.add(new ScheduleEntryVo(date, onDutyLeader, "1", ""));

        // 在周末，值班领导不能参与带班，因此需要从其他领导中选择带班领导
        List<LeaderShiftVo> viceEngineers = currentBatch.stream().filter(u -> StringUtils.equals(u.getPostType(), PostTypeEnum.FZGCS.getCode())).collect(Collectors.toList());
        leadLeader(date, currentBatch, viceEngineers, schedule);
    }

    private static boolean hasAssignedDutyThisMonth(LeaderShiftVo leader, LocalDate date) {
        // 获取当前月份的第一天
        LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());
        // 检查领导在这个月是否已经有一个值班任务
        return leader.getAllAssignedShifts().stream()
                .anyMatch(s -> s.getDate().isAfter(firstDayOfMonth.minusDays(1)) && "1".equals(s.getDutyType()));
    }

    private static void assignDayShifts(LocalDate date, List<LeaderShiftVo> leaders, List<LeaderShiftVo> viceEngineers, List<ScheduleEntryVo> schedule) {
        // 分配值班领导（一天一个班次）
        LeaderShiftVo onDutyLeader = selectOnDutyLeader(date, leaders, false);
        if (onDutyLeader != null) {
            ShiftVo onDutyShift = new ShiftVo(null, date, "1");
            onDutyLeader.assignShift(onDutyShift);
            schedule.add(new ScheduleEntryVo(date, onDutyLeader, "1", null));
        }
        // 分配带班领导（三班倒），并确保矿长和书记各有最多5个带班，副矿长至少7个，副总工程师至少8个
        leadLeader(date, leaders, viceEngineers, schedule);
    }

    private static void leadLeader(LocalDate date, List<LeaderShiftVo> leaders, List<LeaderShiftVo> viceEngineers, List<ScheduleEntryVo> schedule) {
        for (ShiftTypeEnum shift : ShiftTypeEnum.values()) {
            ShiftVo leadShift = new ShiftVo(shift.getName(), date, "2");
            LeaderShiftVo leadLeader = selectLeadLeader(leadShift.getDate(), leaders, leadShift.getShiftType());

            if (leadLeader != null) {
                leadLeader.assignShift(leadShift);
                schedule.add(new ScheduleEntryVo(date, leadLeader, "2", shift.getName()));

                // 如果是矿长或书记带班，安排副总工程师陪同
                if (PostTypeEnum.KZ.getCode().equals(leadLeader.getPostType()) || PostTypeEnum.DWSJ.getCode().equals(leadLeader.getPostType())) {
                    LeaderShiftVo accompanyingViceEngineer = selectAccompanyingViceEngineer(leadShift.getDate(), shift.getName(), viceEngineers);
                    if (accompanyingViceEngineer != null) {
                        accompanyingViceEngineer.assignShift(leadShift);
                        schedule.add(new ScheduleEntryVo(date, accompanyingViceEngineer, "2", shift.getName()));
                    }
                }
            }
        }
    }

    private static LeaderShiftVo selectAccompanyingViceEngineer(LocalDate date, String shiftName, List<LeaderShiftVo> viceEngineers) {
        List<LeaderShiftVo> eligibleViceEngineers = viceEngineers.stream()
                .filter(v -> v.canAssign(new ShiftVo(shiftName, date, "2")))
                .collect(Collectors.toList());
        // 确保优先分配给需要满足最小带班次数的领导
        if (!allLeadersMeetMinShifts(eligibleViceEngineers)) {
            eligibleViceEngineers = eligibleViceEngineers.stream().filter(l -> l.getAssignedLeadShiftsCount() < l.getMinShifts()).collect(Collectors.toList());
            //Collections.shuffle(eligibleViceEngineers, new Random(System.nanoTime()));
            // 找到带班次数最小的 随机取一个
            int minDuty = eligibleViceEngineers.stream().mapToInt(LeaderShiftVo::getAssignedLeadShiftsCount).min().getAsInt();
            eligibleViceEngineers = eligibleViceEngineers.stream().filter(u -> u.getAssignedLeadShiftsCount() == minDuty).collect(Collectors.toList());
            Collections.shuffle(eligibleViceEngineers, new Random(System.nanoTime()));
        } else {
            // 如果所有领导都已经满足了最小带班次数，则尽量平均分配
            eligibleViceEngineers.sort(Comparator.comparingInt(PersonShiftVo::getAssignedLeadShiftsCount)
                    .thenComparingInt(PersonShiftVo::getMaxShifts));
        }


        if (eligibleViceEngineers.isEmpty()) {
            log.info("eligibleViceEngineers is empty,random one");
            eligibleViceEngineers = new ArrayList<>(viceEngineers);
        }

        return eligibleViceEngineers.get(0);
    }

    private static LeaderShiftVo selectLeadLeader(LocalDate date, List<LeaderShiftVo> leaders, String shiftName) {
        List<LeaderShiftVo> eligibleLeaders = leaders.stream()
                .filter(l -> l.canAssign(new ShiftVo(shiftName, date, "2")))
                .collect(Collectors.toList());
        // 确保优先分配给需要满足最小带班次数的领导
        if (!allLeadersMeetMinShifts(eligibleLeaders)) {
            eligibleLeaders = eligibleLeaders.stream().filter(l -> l.getAssignedLeadShiftsCount() < l.getMinShifts()).collect(Collectors.toList());
            Collections.shuffle(eligibleLeaders, new Random(System.nanoTime()));
        } else {
            // 如果所有领导都已经满足了最小带班次数，分配给带/值班次数最少的
            eligibleLeaders.sort(Comparator.comparingInt(PersonShiftVo::getAllAssignedShiftsCount).thenComparingInt(PersonShiftVo::getMaxShifts));
            //Collections.shuffle(eligibleLeaders, new Random(System.nanoTime()));
        }
        if (eligibleLeaders.isEmpty()) {
            System.out.println("eligibleLeaders is empty,random one");
            eligibleLeaders = new ArrayList<>(leaders);
        }
        return eligibleLeaders.get(0);
    }

    // 检查所有领导是否都达到了最低带班次数
    private static boolean allLeadersMeetMinShifts(List<LeaderShiftVo> leaders) {
        return leaders.stream().allMatch(l -> l.getAssignedLeadShiftsCount() >= l.getMinShifts());
    }


    private static LeaderShiftVo selectOnDutyLeader(LocalDate date, List<LeaderShiftVo> leaders, boolean isWeekend) {
        // 所有领导都需参与值班
        // 所有领导都需参与值班，但矿长和书记每月只能有一次值班
        List<LeaderShiftVo> eligibleLeaders = leaders.stream()
                .filter(l -> l.canAssign(new ShiftVo(null, date, "1")))
                .filter(l -> !(l.getPostType().equals(PostTypeEnum.KZ.getCode()) || l.getPostType().equals(PostTypeEnum.DWSJ.getCode())) || !hasAssignedDutyThisMonth(l, date)).sorted(Comparator.comparingInt(LeaderShiftVo::getAssignedDutyCount)).collect(Collectors.toList());
        if (eligibleLeaders.isEmpty()) {
            System.out.println("No suitable leader available for on-duty: " + date);
            eligibleLeaders = new ArrayList<>(leaders);
        }
        // 获取值班次数最少的
        if (isWeekend) {
            // 周末人少  尽量少安排副总工程师值班
            eligibleLeaders.sort(Comparator.comparingInt((LeaderShiftVo u) -> Integer.parseInt(u.getPostType())).reversed());
        } else {
            int minDuty = eligibleLeaders.stream().mapToInt(LeaderShiftVo::getAssignedDutyCount).min().getAsInt();
            eligibleLeaders = eligibleLeaders.stream().filter(u -> u.getAssignedDutyCount() == minDuty).collect(Collectors.toList());
            Collections.shuffle(leaders, new Random(System.nanoTime()));
        }
        return eligibleLeaders.get(0);
    }


    @Override
    public List<DispatchKeepWatchVO> automatictwo(Date beginDate) throws ParseException {

        //根据月份获取当月的天数
        int days = getDaysOfMonth(beginDate);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String nianYue = new SimpleDateFormat("yyyy-MM").format(DateUtils.dateTime("yyyy-MM-dd", dateFormat.format(beginDate)));
//        int countByYearMonth = dispatchKeepWatchMapper.selectCountByYearMonth(nianYue);
        int countMatic = dispatchKeepWatchMapper.countMatic(nianYue);
        if (countMatic >= days) {
//            dispatchKeepWatchMapper.deleteByDate(nianYue);
            throw new HuaNengException(Constants.FAIL, nianYue + "月,已存在班次信息");
        }
        //带班副总 李宏 魏占全  赵琼
        List<DispatchKeepWatchPerson> diabanfuzong = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").eq(DispatchKeepWatchPerson::getPostType, "1").or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "2").orderByAsc(DispatchKeepWatchPerson::getDutyOrder));
        // "杨君", "传金平", "刘贇臣", "马世杰", "岳祥虎", "南雄", "王建辉"
        List<DispatchKeepWatchPerson> putonglingdao = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"2", "3", "4", "5"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "3").orderByAsc(DispatchKeepWatchPerson::getNightOrder));

        List<DispatchKeepWatchPerson> zhongbanlingdao = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"1", "2", "3", "4", "5"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "3").or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "2").orderByAsc(DispatchKeepWatchPerson::getNoonOrder));

        List<DispatchKeepWatchPerson> zaobanlingdao = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"1", "2", "3", "4", "5"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "3").or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "2").orderByDesc(DispatchKeepWatchPerson::getNoonOrder));
        List<DispatchKeepWatchPerson> zaobanld = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"1", "2", "3", "4", "5"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "3").or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "2").orderByAsc(DispatchKeepWatchPerson::getMorningOrder));

        //副矿长
        List<DispatchKeepWatchPerson> zhibanfukangzhang = new ArrayList<>();
//                dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
//                .eq(DispatchKeepWatchPerson::getStatus, "0").eq(DispatchKeepWatchPerson::getPostType,"2").orderByAsc(DispatchKeepWatchPerson::getDutyOrder));
        //矿长和党委书记
        List<DispatchKeepWatchPerson> zhibankangzhuang =
                dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                        .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"6", "7"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "1"));
        for (DispatchKeepWatchPerson d : zhongbanlingdao) {
            if (d.getKeepWatchPersonPost().equals("副矿长")) {
                zhibanfukangzhang.add(d);
            }
        }
        Collections.sort(zhibanfukangzhang, Comparator.comparing(DispatchKeepWatchPerson::getDutyOrder));
        List<DispatchKeepWatchPerson> gkj = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"3", "4", "5"}).orderByAsc(DispatchKeepWatchPerson::getDutyOrder));
        List<DispatchKeepWatchPerson> zhongban = new ArrayList<>();
        List<DispatchKeepWatchPerson> zaoban = new ArrayList<>();
        zhongban.addAll(zhongbanlingdao);
        zaoban.addAll(zaobanld);
        int count = 0;
        Map<Integer, String> mapNight = new HashMap();
        Map<Integer, Object> mapMorning = new HashMap();
        Map<Integer, Object> mapNoon = new HashMap();
        Map<Integer, Object> zhiban = new HashMap();


        int u = 2;
        int n = 1;
        for (int f = 0; f < 5; f++) {
            for (int t = 0; t < diabanfuzong.size(); t++) {
                int c = 0;
                int i = 0;
                ok:
                for (i = 1; i <= days; i++) {
                    if (i == u) {
                        u = u + 2;
//                        System.out.println(i + "-" + strs[t]);
                        mapNight.put(i, diabanfuzong.get(t).getKeepWatchPersonId());
                        if (c == 0) {
                            c = 0;
                            break ok;
                        }
                        c++;
                    }
                }
            }
        }
        //普通领导
        int o = 0;
        for (int i = 1; i <= days; i++) {
            if (n == i) {
                n = n + 2;
                if (o > putonglingdao.size() - 1) {
                    o = 0;
                }
                mapNight.put(i, putonglingdao.get(o).getKeepWatchPersonId());
                o++;
            }
        }
        //中班
        for (int j = 1; j <= days; j++) {
            if (zhongbanlingdao.size() > 0) {
                zhongbanlingdao.addAll(zhongban);
            }
            for (int h = 0; h < zhongbanlingdao.size(); h++) {
                if (!mapNight.get(j).equals(zhongbanlingdao.get(h).getKeepWatchPersonId())) {
                    mapNoon.put(j, zhongbanlingdao.get(h).getKeepWatchPersonId());
                    zhongbanlingdao.remove(h);
                    break;
                }
            }
        }
        //        早班
        for (int j = 1; j <= days; j++) {
            if (zaobanlingdao.size() > 0) {
                zaobanlingdao.addAll(zaobanld);
            }
            for (int m = 0; m < zaobanlingdao.size(); m++) {
                if (!mapNight.get(j).equals(zaobanlingdao.get(m).getKeepWatchPersonId()) && !mapNoon.get(j).equals(zaobanlingdao.get(m).getKeepWatchPersonId())) {
                    mapMorning.put(j, zaobanlingdao.get(m).getKeepWatchPersonId());
                    zaobanlingdao.remove(m);
                    break;
                }
            }
        }
//            }
//        }
        //值班
//        String[] strs1 = {"马世杰", "南雄", "王建辉", "刘贇臣"};
        int u1 = 2;
        for (int f = 0; f < 4; f++) {
            for (int t = 0; t < zhibanfukangzhang.size(); t++) {
                int c = 0;
                int i = 0;
                ok:
                for (i = 1; i <= 30; i++) {
                    if (i == u1) {
                        u1 = u1 + 1;
                        String name = zhibanfukangzhang.get(t).getKeepWatchPersonId();
                        if (!mapNight.get(i).equals(name) && !mapMorning.get(i).equals(name) && !mapNoon.get(i).equals(name)) {
                            zhiban.put(i, zhibanfukangzhang.get(t).getKeepWatchPersonId());
                            if (c == 0) {
                                c = 0;
                                break ok;
                            }
                            c++;
                        }
                    }
                }
            }
        }

        int u3 = 2;
        int uu = 0;
        for (int f = 0; f < 2; f++) {
            for (int t = 0; t < zhibankangzhuang.size(); t++) {
                int c = 0;
                int i = 0;
                ok:
                for (i = 1; i <= 30; i++) {
                    if (i == u3 && uu < 4) {
                        u3 = u3 + 1;
                        if (zhiban.get(i) == null) {
                            zhiban.put(i, zhibankangzhuang.get(t).getKeepWatchPersonId());
                            uu++;
                            if (uu == 2) {
                                u3 = 17;
                                i = 16;
                            }
                            if (uu == 1) {
                                u3 = 5;
                            }
                            if (c == 1) {
                                c = 0;
                                break ok;
                            }
                            c++;
                        }
                    }
                }
            }
        }

        int u2 = 1;
        for (int f = 0; f < 3; f++) {
            ol:
            for (int t = 0; t < gkj.size(); t++) {
                int c = 0;
                int i = 0;
                ok:
                for (i = 1; i <= days; i++) {
                    if (i == u2) {
                        u2 = u2 + 1;
                        if (u2 >= 32) {
                            u2 = 30;
                        } else {
                            u2 = u2;
                        }
                        if (zhiban.get(i) == null && !mapNight.get(i).equals(gkj.get(t).getKeepWatchPersonId()) && !mapMorning.get(i).equals(gkj.get(t).getKeepWatchPersonId()) && !mapNoon.get(i).equals(gkj.get(t).getKeepWatchPersonId())) {

                            zhiban.put(i, gkj.get(t).getKeepWatchPersonId());
                            if (c == 1) {
                                c = 0;
                                break ok;
                            }
                            c++;
                        }
                    }
                }
            }
        }

        Random random = new Random();
        int index = random.nextInt(gkj.size());
        System.out.println(index);
        for (int i = 1; i <= days; i++) {
            if (zhiban.get(i) == null && !mapNight.get(i).equals(gkj.get(index).getKeepWatchPersonId()) && !mapMorning.get(i).equals(gkj.get(index).getKeepWatchPersonId()) && !mapNoon.get(i).equals(gkj.get(index).getKeepWatchPersonId())) {
                zhiban.put(i, gkj.get(index).getKeepWatchPersonId());
            } else if (zhiban.get(i) == null && (mapNight.get(i).equals(gkj.get(index).getKeepWatchPersonId()) || !mapMorning.get(i).equals(gkj.get(index).getKeepWatchPersonId()) && !mapNoon.get(i).equals(gkj.get(index).getKeepWatchPersonId()))) {
                if (index - 1 < 0) {
                    index = 2;
                }
                zhiban.put(i, gkj.get(index).getKeepWatchPersonId());
            }
        }


        System.out.println(mapMorning + "\t");
        System.out.println(mapNoon + "\t");
        System.out.println(mapNight + "\t");
        System.out.println(zhiban + "\t");
        DispatchKeepWatch dispatchKeepWatch = null;
        String zao = getShiftList("早班");
        String zhong = getShiftList("中班");
        String wan = getShiftList("晚班");
        for (Integer key : mapMorning.keySet()) {
            dispatchKeepWatch = new DispatchKeepWatch();
            String date = nianYue + "-" + key;
            System.out.println("key= " + date + " and value= " + mapMorning.get(key));
            try {
                dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                dispatchKeepWatch.setShiftId(zao);
                dispatchKeepWatch.setType("2");
                dispatchKeepWatch.setLeadPersonIds(mapMorning.get(key).toString());
                dispatchKeepWatch.setDelFlag("0");
                dispatchKeepWatchMapper.insert(dispatchKeepWatch);
            } catch (Exception e) {
                throw e;
            }
        }
        for (Integer key : mapNoon.keySet()) {
            dispatchKeepWatch = new DispatchKeepWatch();
            String date = nianYue + "-" + key;
//            System.out.println("key= " +date + " and value= " + mapNoon.get(key));
            try {
                dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                dispatchKeepWatch.setShiftId(zhong);
                dispatchKeepWatch.setType("2");
                dispatchKeepWatch.setLeadPersonIds(mapNoon.get(key).toString());
                dispatchKeepWatch.setDelFlag("0");
                dispatchKeepWatchMapper.insert(dispatchKeepWatch);
            } catch (Exception e) {
                throw e;
            }
        }
        for (Integer key : mapNight.keySet()) {
            dispatchKeepWatch = new DispatchKeepWatch();
            String date = nianYue + "-" + key;
//            System.out.println("key= " +date + " and value= " + mapNight.get(key));
            try {
                dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                dispatchKeepWatch.setShiftId(wan);
                dispatchKeepWatch.setType("2");
                dispatchKeepWatch.setLeadPersonIds(mapNight.get(key).toString());
                dispatchKeepWatch.setDelFlag("0");
                dispatchKeepWatchMapper.insert(dispatchKeepWatch);
            } catch (Exception e) {
                throw e;
            }
        }
        for (Integer key : zhiban.keySet()) {
            dispatchKeepWatch = new DispatchKeepWatch();
            String date = nianYue + "-" + key;
//            System.out.println("key= " +date + " and value= " + zhiban.get(key));
            try {
                dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
//                dispatchKeepWatch.setShiftId(wan);
                dispatchKeepWatch.setType("1");
                dispatchKeepWatch.setDutyPersonIds(zhiban.get(key).toString());
                dispatchKeepWatch.setDelFlag("0");
                dispatchKeepWatchMapper.insert(dispatchKeepWatch);
            } catch (Exception e) {
                throw e;
            }
        }
        return null;
    }

    @Override
    public List<DispatchKeepWatchVO> automaticLD(Date beginDate) throws ParseException {


        //根据月份获取当月的天数
        int days = getDaysOfMonth(beginDate);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String nianYue = new SimpleDateFormat("yyyy-MM").format(DateUtils.dateTime("yyyy-MM-dd", dateFormat.format(beginDate)));
//        int countByYearMonth = dispatchKeepWatchMapper.selectCountByYearMonth(nianYue);
        int countMatic = dispatchKeepWatchMapper.countMatic(nianYue);
        if (countMatic >= days) {
//            dispatchKeepWatchMapper.deleteByDate(nianYue);
            throw new HuaNengException(Constants.FAIL, nianYue + "月,已存在班次信息");
        }
        //带班副总 李宏 魏占全  赵琼
        List<DispatchKeepWatchPerson> diabanfuzong = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").eq(DispatchKeepWatchPerson::getPostType, "1").or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "2").orderByAsc(DispatchKeepWatchPerson::getDutyOrder));
        // "杨君", "传金平", "刘贇臣", "马世杰", "岳祥虎", "南雄", "王建辉"
        List<DispatchKeepWatchPerson> putonglingdao = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"2", "3", "4", "5"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "3").orderByAsc(DispatchKeepWatchPerson::getNightOrder));

        List<DispatchKeepWatchPerson> zhongbanlingdao = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"1", "2", "3", "4", "5"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "3").or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "2").orderByAsc(DispatchKeepWatchPerson::getNoonOrder));

        List<DispatchKeepWatchPerson> zaobanlingdao = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"1", "2", "3", "4", "5"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "3").or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "2").orderByDesc(DispatchKeepWatchPerson::getNoonOrder));
        List<DispatchKeepWatchPerson> zaobanld = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"1", "2", "3", "4", "5"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "3").or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "2").orderByAsc(DispatchKeepWatchPerson::getMorningOrder));

        //副矿长
        List<DispatchKeepWatchPerson> zhibanfukangzhang = new ArrayList<>();
//                dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
//                .eq(DispatchKeepWatchPerson::getStatus, "0").eq(DispatchKeepWatchPerson::getPostType,"2").orderByAsc(DispatchKeepWatchPerson::getDutyOrder));
        //矿长和党委书记
        List<DispatchKeepWatchPerson> zhibankangzhuang =
                dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                        .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"6", "7"}).or().eq(DispatchKeepWatchPerson::getKeepWatchPersonType, "1"));
        for (DispatchKeepWatchPerson d : zhongbanlingdao) {
            if (d.getKeepWatchPersonPost().equals("副矿长")) {
                zhibanfukangzhang.add(d);
            }
        }
        Collections.sort(zhibanfukangzhang, Comparator.comparing(DispatchKeepWatchPerson::getDutyOrder));
        List<DispatchKeepWatchPerson> gkj = dispatchKeepWatchPersonMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatchPerson>()
                .eq(DispatchKeepWatchPerson::getStatus, "0").in(DispatchKeepWatchPerson::getPostType, new String[]{"3", "4", "5"}).orderByAsc(DispatchKeepWatchPerson::getDutyOrder));
        List<DispatchKeepWatchPerson> zhongban = new ArrayList<>();
        List<DispatchKeepWatchPerson> zaoban = new ArrayList<>();
        zhongban.addAll(zhongbanlingdao);
        zaoban.addAll(zaobanld);
        int count = 0;
        Map<Integer, String> mapNight = new HashMap();
        Map<Integer, Object> mapMorning = new HashMap();
        Map<Integer, Object> mapNoon = new HashMap();
        Map<Integer, Object> zhiban = new HashMap();


        int u = 2;
        int n = 1;
        for (int f = 0; f < 5; f++) {
            for (int t = 0; t < diabanfuzong.size(); t++) {
                int c = 0;
                int i = 0;
                ok:
                for (i = 1; i <= days; i++) {
                    if (i == u) {
                        u = u + 2;
//                        System.out.println(i + "-" + strs[t]);
                        mapNight.put(i, diabanfuzong.get(t).getKeepWatchPersonId());
                        if (c == 0) {
                            c = 0;
                            break ok;
                        }
                        c++;
                    }
                }
            }
        }
        //普通领导
        int o = 0;
        for (int i = 1; i <= days; i++) {
            if (n == i) {
                n = n + 2;
                if (o > putonglingdao.size() - 1) {
                    o = 0;
                }
                mapNight.put(i, putonglingdao.get(o).getKeepWatchPersonId());
                o++;
            }
        }
        //中班
        for (int j = 1; j <= days; j++) {
            if (zhongbanlingdao.size() > 0) {
                zhongbanlingdao.addAll(zhongban);
            }
            for (int h = 0; h < zhongbanlingdao.size(); h++) {
                if (!mapNight.get(j).equals(zhongbanlingdao.get(h).getKeepWatchPersonId())) {
                    mapNoon.put(j, zhongbanlingdao.get(h).getKeepWatchPersonId());
                    zhongbanlingdao.remove(h);
                    break;
                }
            }
        }
        //        早班
        for (int j = 1; j <= days; j++) {
            if (zaobanlingdao.size() > 0) {
                zaobanlingdao.addAll(zaobanld);
            }
            for (int m = 0; m < zaobanlingdao.size(); m++) {
                if (!mapNight.get(j).equals(zaobanlingdao.get(m).getKeepWatchPersonId()) && !mapNoon.get(j).equals(zaobanlingdao.get(m).getKeepWatchPersonId())) {
                    mapMorning.put(j, zaobanlingdao.get(m).getKeepWatchPersonId());
                    zaobanlingdao.remove(m);
                    break;
                }
            }
        }
//            }
//        }
        //值班
//        String[] strs1 = {"马世杰", "南雄", "王建辉", "刘贇臣"};
        int u1 = 2;
        for (int f = 0; f < 4; f++) {
            for (int t = 0; t < zhibanfukangzhang.size(); t++) {
                int c = 0;
                int i = 0;
                ok:
                for (i = 1; i <= 30; i++) {
                    if (i == u1) {
                        u1 = u1 + 1;
                        String name = zhibanfukangzhang.get(t).getKeepWatchPersonId();
                        if (!mapNight.get(i).equals(name) && !mapMorning.get(i).equals(name) && !mapNoon.get(i).equals(name)) {
                            zhiban.put(i, zhibanfukangzhang.get(t).getKeepWatchPersonId());
                            if (c == 0) {
                                c = 0;
                                break ok;
                            }
                            c++;
                        }
                    }
                }
            }
        }

        int u3 = 2;
        int uu = 0;
        for (int f = 0; f < 2; f++) {
            for (int t = 0; t < zhibankangzhuang.size(); t++) {
                int c = 0;
                int i = 0;
                ok:
                for (i = 1; i <= 30; i++) {
                    if (i == u3 && uu < 4) {
                        u3 = u3 + 1;
                        if (zhiban.get(i) == null) {
                            zhiban.put(i, zhibankangzhuang.get(t).getKeepWatchPersonId());
                            uu++;
                            if (uu == 2) {
                                u3 = 17;
                                i = 16;
                            }
                            if (uu == 1) {
                                u3 = 5;
                            }
                            if (c == 1) {
                                c = 0;
                                break ok;
                            }
                            c++;
                        }
                    }
                }
            }
        }

        int u2 = 1;
        for (int f = 0; f < 3; f++) {
            ol:
            for (int t = 0; t < gkj.size(); t++) {
                int c = 0;
                int i = 0;
                ok:
                for (i = 1; i <= days; i++) {
                    if (i == u2) {
                        u2 = u2 + 1;
                        if (u2 >= 32) {
                            u2 = 30;
                        } else {
                            u2 = u2;
                        }
                        if (zhiban.get(i) == null && !mapNight.get(i).equals(gkj.get(t).getKeepWatchPersonId()) && !mapMorning.get(i).equals(gkj.get(t).getKeepWatchPersonId()) && !mapNoon.get(i).equals(gkj.get(t).getKeepWatchPersonId())) {

                            zhiban.put(i, gkj.get(t).getKeepWatchPersonId());
                            if (c == 1) {
                                c = 0;
                                break ok;
                            }
                            c++;
                        }
                    }
                }
            }
        }

        Random random = new Random();
        int index = random.nextInt(gkj.size());
        System.out.println(index);
        for (int i = 1; i <= days; i++) {
            if (zhiban.get(i) == null && !mapNight.get(i).equals(gkj.get(index).getKeepWatchPersonId()) && !mapMorning.get(i).equals(gkj.get(index).getKeepWatchPersonId()) && !mapNoon.get(i).equals(gkj.get(index).getKeepWatchPersonId())) {
                zhiban.put(i, gkj.get(index).getKeepWatchPersonId());
            } else if (zhiban.get(i) == null && (mapNight.get(i).equals(gkj.get(index).getKeepWatchPersonId()) || !mapMorning.get(i).equals(gkj.get(index).getKeepWatchPersonId()) && !mapNoon.get(i).equals(gkj.get(index).getKeepWatchPersonId()))) {
                if (index - 1 < 0) {
                    index = 2;
                }
                zhiban.put(i, gkj.get(index).getKeepWatchPersonId());
            }
        }


        System.out.println(mapMorning + "\t");
        System.out.println(mapNoon + "\t");
        System.out.println(mapNight + "\t");
        System.out.println(zhiban + "\t");
        DispatchKeepWatch dispatchKeepWatch = null;
        String zao = getShiftList("头班");
        String zhong = getShiftList("二班");
        String wan = getShiftList("三班");
        for (Integer key : mapMorning.keySet()) {
            dispatchKeepWatch = new DispatchKeepWatch();
            String date = nianYue + "-" + key;
            System.out.println("key= " + date + " and value= " + mapMorning.get(key));
            try {
                dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                dispatchKeepWatch.setShiftId(zao);
                dispatchKeepWatch.setType("2");
                dispatchKeepWatch.setLeadPersonIds(mapMorning.get(key).toString());
                dispatchKeepWatch.setDelFlag("0");
                dispatchKeepWatchMapper.insert(dispatchKeepWatch);
            } catch (Exception e) {
                throw e;
            }
        }
        for (Integer key : mapNoon.keySet()) {
            dispatchKeepWatch = new DispatchKeepWatch();
            String date = nianYue + "-" + key;
//            System.out.println("key= " +date + " and value= " + mapNoon.get(key));
            try {
                dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                dispatchKeepWatch.setShiftId(zhong);
                dispatchKeepWatch.setType("2");
                dispatchKeepWatch.setLeadPersonIds(mapNoon.get(key).toString());
                dispatchKeepWatch.setDelFlag("0");
                dispatchKeepWatchMapper.insert(dispatchKeepWatch);
            } catch (Exception e) {
                throw e;
            }
        }
        for (Integer key : mapNight.keySet()) {
            dispatchKeepWatch = new DispatchKeepWatch();
            String date = nianYue + "-" + key;
//            System.out.println("key= " +date + " and value= " + mapNight.get(key));
            try {
                dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                dispatchKeepWatch.setShiftId(wan);
                dispatchKeepWatch.setType("2");
                dispatchKeepWatch.setLeadPersonIds(mapNight.get(key).toString());
                dispatchKeepWatch.setDelFlag("0");
                dispatchKeepWatchMapper.insert(dispatchKeepWatch);
            } catch (Exception e) {
                throw e;
            }
        }
        for (Integer key : zhiban.keySet()) {
            dispatchKeepWatch = new DispatchKeepWatch();
            String date = nianYue + "-" + key;
//            System.out.println("key= " +date + " and value= " + zhiban.get(key));
            try {
                dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
//                dispatchKeepWatch.setShiftId(wan);
                dispatchKeepWatch.setType("1");
                dispatchKeepWatch.setDutyPersonIds(zhiban.get(key).toString());
                dispatchKeepWatch.setDelFlag("0");
                dispatchKeepWatchMapper.insert(dispatchKeepWatch);
            } catch (Exception e) {
                throw e;
            }
        }
        return null;
    }

    @Override
    public List<DispatchKeepWatchVO> automaticgty(Date beginDate, String mineCode) throws ParseException {
        int days = getDaysOfMonth(beginDate);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String zao = getShiftList("早班");
        String zhong = getShiftList("中班");
        String wan = getShiftList("晚班");
        DispatchKeepWatch dispatchKeepWatch = null;
        List<DispatchKeepWatchPersonVO> list = dispatchKeepWatchPersonMapper.selectWatchPerson("1");
        List<DispatchKeepWatchPersonVO> list2 = dispatchKeepWatchPersonMapper.selectWatchPerson("2");
        if (list == null || list2 == null) {
            throw new HuaNengException(Constants.FAIL, "排班人员为空");
        }

        String nianYue = new SimpleDateFormat("yyyy-MM").format(DateUtils.dateTime("yyyy-MM-dd", dateFormat.format(beginDate)));
        for (int j = 0; j <= 2; j++) {
            if (j == 0) {
                for (int i = 1; i <= 31; i++) {
                    dispatchKeepWatch = new DispatchKeepWatch();
                    String date = nianYue + "-" + i;
                    try {
                        dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                        dispatchKeepWatch.setShiftId(wan);
                        dispatchKeepWatch.setType("2");
//                String[] str3 = {"赵忠理","生产任月旺", "安全赵慧", "掘进陈靖", "机电马振宇", "机电副于西广", "地测副杨红科","采煤副王瑞光","机电副巍金龙","安全副刘帅"};

                        if (i == 12) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(0).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("赵忠理");
                        } else if (i == 4 || i == 28) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(1).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("任月旺");
                        } else if (i == 2 || i == 20) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(2).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("赵慧");
                        } else if (i == 7 || i == 30) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(3).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("陈靖");
                        } else if (i == 13 || i == 26) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(4).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("马振宇");
                        } else if (i == 6 || i == 11 || i == 15 || i == 21) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(5).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("于西广");
                        } else if (i == 5 || i == 8 || i == 17 || i == 24 || i == 31) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(6).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("杨红科");
                        } else if (i == 3 || i == 9 || i == 27 || i == 23 || i == 29) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(7).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("王瑞光");
                        } else if (i == 14 || i == 18 || i == 22 || i == 25) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(8).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("巍金龙");
                        } else if (i == 1 || i == 10 || i == 16 || i == 19) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(9).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("刘帅");
                        }
//                        dispatchKeepWatch.setKeepWatchName("");
                        dispatchKeepWatch.setDelFlag("0");
                        dispatchKeepWatch.setMineCode(mineCode);
                        dispatchKeepWatchMapper.insert(dispatchKeepWatch);
                    } catch (Exception e) {
                        throw e;
                    }
                }
            } else if (j == 1) {
                for (int i = 1; i <= 31; i++) {
                    dispatchKeepWatch = new DispatchKeepWatch();
                    String date = nianYue + "-" + i;
                    try {
                        dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                        dispatchKeepWatch.setShiftId(zao);
                        dispatchKeepWatch.setType("2");
//                String[] str3 = {"赵忠理","生产任月旺", "安全赵慧", "掘进陈靖", "机电马振宇", "机电副于西广", "地测副杨红科","采煤副王瑞光","机电副巍金龙","安全副刘帅"};

                        if (i == 5 || i == 16 || i == 21) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(0).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("赵忠理");
                        } else if (i == 10 || i == 13 || i == 24) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(1).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("任月旺");
                        } else if (i == 7 || i == 11 || i == 17) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(2).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("赵慧");
                        } else if (i == 2 || i == 9 || i == 25) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(3).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("陈靖");
                        } else if (i == 19 || i == 23 || i == 31) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(4).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("马振宇");
                        } else if (i == 4 || i == 18 || i == 26 || i == 30) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(5).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("于西广");
                        } else if (i == 1 || i == 3 || i == 22 || i == 27) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(6).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("杨红科");
                        } else if (i == 12 || i == 15) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(7).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("王瑞光");
                        } else if (i == 6 || i == 20 || i == 29) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(8).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("巍金龙");
                        } else if (i == 8 || i == 14 || i == 28) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(9).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("刘帅");
                        }
//                        dispatchKeepWatch.setKeepWatchName("");
                        dispatchKeepWatch.setDelFlag("0");
                        dispatchKeepWatch.setMineCode(mineCode);
                        dispatchKeepWatchMapper.insert(dispatchKeepWatch);
                    } catch (Exception e) {
                        throw e;
                    }
                }
            } else {
                //中班
                for (int i = 1; i <= 31; i++) {
                    dispatchKeepWatch = new DispatchKeepWatch();
                    String date = nianYue + "-" + i;
                    try {
                        dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                        dispatchKeepWatch.setShiftId(zhong);
                        dispatchKeepWatch.setType("2");
//                String[] str3 = {"赵忠理","生产任月旺", "安全赵慧", "掘进陈靖", "机电马振宇", "机电副于西广", "地测副杨红科","采煤副王瑞光","机电副巍金龙","安全副刘帅"};

                        if (i == 26) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(0).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("赵忠理");
                        } else if (i == 6 || i == 17 || i == 30) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(1).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("任月旺");
                        } else if (i == 4 || i == 23 || i == 29) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(2).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("赵慧");
                        } else if (i == 11 || i == 14 || i == 19) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(3).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("陈靖");
                        } else if (i == 2 || i == 9 || i == 16) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(4).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("马振宇");
                        } else if (i == 7 || i == 24 || i == 28) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(5).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("于西广");
                        } else if (i == 10 || i == 13 || i == 20) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(6).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("杨红科");
                        } else if (i == 5 || i == 18 || i == 21 || i == 31) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(7).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("王瑞光");
                        } else if (i == 1 || i == 8 || i == 15 || i == 27) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(8).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("巍金龙");
                        } else if (i == 3 || i == 12 || i == 22 || i == 25) {
                            dispatchKeepWatch.setLeadPersonIds(list.get(9).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("刘帅");
                        }
//                        dispatchKeepWatch.setKeepWatchName("");
                        dispatchKeepWatch.setDelFlag("0");
                        dispatchKeepWatch.setMineCode(mineCode);
                        dispatchKeepWatchMapper.insert(dispatchKeepWatch);
                    } catch (Exception e) {
                        throw e;
                    }
                }
            }
        }
        //普通员工
        for (int j = 0; j <= 2; j++) {
            if (j == 0) {
                for (int i = 1; i <= 31; i++) {
                    dispatchKeepWatch = new DispatchKeepWatch();
                    String date = nianYue + "-" + i;
                    try {
                        dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                        dispatchKeepWatch.setShiftId(wan);
                        dispatchKeepWatch.setType("2");
//                String[] str3 = {"赵忠理","生产任月旺", "安全赵慧", "掘进陈靖", "机电马振宇", "机电副于西广", "地测副杨红科","采煤副王瑞光","机电副巍金龙","安全副刘帅"};

                        if (i == 1 || i == 28) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(0).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("于海");
                        } else if (i == 15 || i == 25) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(1).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("周得梁");
                        } else if (i == 5 || i == 27 || i == 31) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(2).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("李亮亮");
                        } else if (i == 7 || i == 23) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(3).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("汪兴斌");
                        } else if (i == 12 || i == 19) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(4).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("郝向虎");
                        } else if (i == 6 || i == 24) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(5).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("孙鹏飞");
                        } else if (i == 9 || i == 21) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(6).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("项浩帆");
                        } else if (i == 8 || i == 22) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(7).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("孙明");
                        } else if (i == 20 || i == 29) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(8).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("韩双浩");
                        } else if (i == 13 || i == 17) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(9).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("于二利");
                        } else if (i == 3 || i == 18) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(10).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("乔治");
                        } else if (i == 2 || i == 10) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(11).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("任瑞华");
                        } else if (i == 11 || i == 26) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(12).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("康永明");
                        } else if (i == 14 || i == 30) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(13).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("赵斌");
                        } else if (i == 4 || i == 16) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(14).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("王伟嘉");
                        }
//                        dispatchKeepWatch.setKeepWatchName("");
                        dispatchKeepWatch.setDelFlag("0");
                        dispatchKeepWatch.setMineCode(mineCode);
                        dispatchKeepWatchMapper.insert(dispatchKeepWatch);
                    } catch (Exception e) {
                        throw e;
                    }
                }
            } else if (j == 1) {
                for (int i = 1; i <= 31; i++) {
                    dispatchKeepWatch = new DispatchKeepWatch();
                    String date = nianYue + "-" + i;
                    try {
                        dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                        dispatchKeepWatch.setShiftId(zao);
                        dispatchKeepWatch.setType("2");
//                String[] str3 = {"赵忠理","生产任月旺", "安全赵慧", "掘进陈靖", "机电马振宇", "机电副于西广", "地测副杨红科","采煤副王瑞光","机电副巍金龙","安全副刘帅"};

                        if (i == 13 || i == 16) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(0).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("于海");
                        } else if (i == 6 || i == 12) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(1).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("周得梁");
                        } else if (i == 11 || i == 21) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(2).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("李亮亮");
                        } else if (i == 17 || i == 27) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(3).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("汪兴斌");
                        } else if (i == 1 || i == 8) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(4).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("郝向虎");
                        } else if (i == 10 || i == 20 || i == 31) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(5).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("孙鹏飞");
                        } else if (i == 3 || i == 15) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(6).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("项浩帆");
                        } else if (i == 18 || i == 30) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(7).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("孙明");
                        } else if (i == 14 || i == 25) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(8).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("韩双浩");
                        } else if (i == 5 || i == 23) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(9).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("于二利");
                        } else if (i == 7 || i == 28) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(10).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("乔治");
                        } else if (i == 4 || i == 26) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(11).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("任瑞华");
                        } else if (i == 22 || i == 29) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(12).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("康永明");
                        } else if (i == 2 || i == 19) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(13).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("赵斌");
                        } else if (i == 9 || i == 24) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(14).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("王伟嘉");
                        }
//                        dispatchKeepWatch.setKeepWatchName("");
                        dispatchKeepWatch.setDelFlag("0");
                        dispatchKeepWatch.setMineCode(mineCode);
                        dispatchKeepWatchMapper.insert(dispatchKeepWatch);
                    } catch (Exception e) {
                        throw e;
                    }
                }
            } else {
                //中班
                for (int i = 1; i <= 31; i++) {
                    dispatchKeepWatch = new DispatchKeepWatch();
                    String date = nianYue + "-" + i;
                    try {
                        dispatchKeepWatch.setKeepWatchDate(dateFormat.parse(date));
                        dispatchKeepWatch.setShiftId(zhong);
                        dispatchKeepWatch.setType("2");
//                String[] str3 = {"赵忠理","生产任月旺", "安全赵慧", "掘进陈靖", "机电马振宇", "机电副于西广", "地测副杨红科","采煤副王瑞光","机电副巍金龙","安全副刘帅"};

                        if (i == 7 || i == 22) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(0).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("于海");
                        } else if (i == 3 || i == 18) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(1).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("周得梁");
                        } else if (i == 17 || i == 23) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(2).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("李亮亮");
                        } else if (i == 2 || i == 13) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(3).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("汪兴斌");
                        } else if (i == 15 || i == 29) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(4).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("郝向虎");
                        } else if (i == 14 || i == 28) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(5).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("孙鹏飞");
                        } else if (i == 12 || i == 27) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(6).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("项浩帆");
                        } else if (i == 1 || i == 5 || i == 11) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(7).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("孙明");
                        } else if (i == 4 || i == 16) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(8).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("韩双浩");
                        } else if (i == 8 || i == 31) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(9).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("于二利");
                        } else if (i == 20 || i == 24) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(10).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("乔治");
                        } else if (i == 19 || i == 30) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(11).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("任瑞华");
                        } else if (i == 6 || i == 9) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(12).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("康永明");
                        } else if (i == 10 || i == 25) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(13).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("赵斌");
                        } else if (i == 21 || i == 26) {
                            dispatchKeepWatch.setLeadPersonIds(list2.get(14).getKeepWatchPersonId());
//                            dispatchKeepWatch.setKeepWatchName("王伟嘉");
                        }
//                        dispatchKeepWatch.setKeepWatchName("");
                        dispatchKeepWatch.setDelFlag("0");
                        dispatchKeepWatch.setMineCode(mineCode);
                        dispatchKeepWatchMapper.insert(dispatchKeepWatch);
                    } catch (Exception e) {
                        throw e;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取某个月的天数
     *
     * @param date
     * @return
     */
    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    public String getShiftList(String shift) {
        DynamicDataSourceContextHolder.push("slave");
        List<DimShift> shiftList = dimShiftMapper.selectList(new LambdaQueryWrapper<DimShift>()
                .eq(DimShift::getStatus, "0").eq(DimShift::getShiftName, shift).orderByAsc(DimShift::getShiftStartTime));
        DynamicDataSourceContextHolder.clear();
        if (CollUtil.isEmpty(shiftList)) {
            throw new HuaNengException(Constants.FAIL, "班次信息不存在");
        }
        String shifts = "";
        for (DimShift dimShift : shiftList) {
            if (dimShift.getShiftName().equals(shift)) {
                shifts = dimShift.getShiftId();
            }
        }
        return shifts;
    }

    /**
     * 随机分配带班人员
     *
     * @param rankScores
     * @param leadList         现有带班人员
     * @param oldLeadPersons   上一轮的带班人员
     * @param lastDutyPersonId 上一轮的值班人员
     * @param nowDutyPersonId  当前轮的值班人员
     * @param number           班次人数
     * @return 分配的带班人员集合
     */
    private List<DispatchKeepWatchPerson> randomLeadPersons(List<RankScore> rankScores,
                                                            LinkedList<DispatchKeepWatchPerson> leadList, List<RankScore> oldLeadPersons, String lastDutyPersonId, String nowDutyPersonId, Integer number) {

        Map<String, DispatchKeepWatchPerson> leadMap = leadList.stream().collect(Collectors.toMap(DispatchKeepWatchPerson::getKeepWatchPersonId, Function.identity()));
        //第一次选人
        Set<String> resultPersonIds = new HashSet<>();
        choosePersonId(RankScore.orderAsc(rankScores), resultPersonIds, number, nowDutyPersonId, lastDutyPersonId, oldLeadPersons);
        //添加分值和优先级
        addScoreAndPriority(rankScores, resultPersonIds);
        //第二次选人
        if (resultPersonIds.size() < number) {
            //弹出第一个
            if (CollUtil.isNotEmpty(oldLeadPersons)) {
                oldLeadPersons = RankScore.orderAsc(oldLeadPersons);
            }
            Set<String> result2 = choosePersonId(RankScore.orderAsc(rankScores), resultPersonIds, number, nowDutyPersonId, lastDutyPersonId, oldLeadPersons);
            //添加分值和优先级
            addScoreAndPriority(rankScores, result2);
            //最后一次选人
            if (resultPersonIds.size() < number) {
                Set<String> result3 = choosePersonId(RankScore.orderAsc(rankScores), resultPersonIds, number, nowDutyPersonId, StrUtil.EMPTY, ListUtil.empty());
                //添加分值和优先级
                addScoreAndPriority(rankScores, result3);
            }
        }
        if (resultPersonIds.size() < number) {
            throw new HuaNengException(Constants.FAIL, "人员不足分配");
        }
        return resultPersonIds.stream().map(leadMap::get).collect(Collectors.toList());
    }

    /**
     * 选人
     *
     * @param rankScores
     * @param resultPersonIds
     * @param number
     * @param nowDutyPersonId
     * @param lastDutyPersonId
     * @param oldLeadPersons
     * @return
     */
    private Set<String> choosePersonId(List<RankScore> rankScores, Set<String> resultPersonIds, Integer number, String nowDutyPersonId, String lastDutyPersonId, List<RankScore> oldLeadPersons) {
        for (RankScore rankScore : rankScores) {
            if (resultPersonIds.size() < number && !resultPersonIds.contains(rankScore.getKey()) && !StrUtil.equals(rankScore.getKey(), nowDutyPersonId)) {
                boolean flag = false;
                //是否上一轮的值班人员
                if (StrUtil.equals(rankScore.getKey(), lastDutyPersonId)) {
                    //暂时跳过
                    flag = true;
                }
                //是否是上一轮带班人员
                if (oldLeadPersons.stream().anyMatch(o -> o.getKey().equals(rankScore.getKey()))) {
                    flag = true;
                }
                if (!flag) {
                    resultPersonIds.add(rankScore.getKey());
                }
            }
        }
        return resultPersonIds;
    }


    /**
     * 加分加优先级
     *
     * @param rankScores
     * @param key
     * @param score
     * @param priority
     */
    private static void addScoreAndPriority(List<RankScore> rankScores, String key, Integer score, Integer priority) {
        for (RankScore rankScore : rankScores) {
            if (rankScore.getKey().equals(key)) {
                rankScore.setScore(rankScore.getScore() + score);
                rankScore.setPriority(rankScore.getPriority() + priority);
                break;
            }
        }
    }

    /**
     * 加分加优先级
     *
     * @param rankScores
     * @param keys
     */
    private static void addScoreAndPriority(List<RankScore> rankScores, Set<String> keys) {
        //同分的分在一组
        Map<Integer, List<RankScore>> scoreMap = new HashMap<>();
        for (String key : keys) {
            RankScore rankScore = rankScores.stream().filter(o -> o.getKey().equals(key)).findFirst().orElse(null);
            if (rankScore != null) {
                List<RankScore> exists = scoreMap.getOrDefault(rankScore.getScore(), new ArrayList<>());
                exists.add(rankScore);
                scoreMap.put(rankScore.getScore(), exists);
            }
        }
        //同分的随机加点.
        scoreMap.forEach((k, v) -> {
            LinkedHashSet<Integer> sets = new LinkedHashSet<>();
            while (sets.size() < v.size()) {
                sets.add(RandomUtil.randomInt(-100, 100));
            }
            for (RankScore rankScore : rankScores) {
                for (RankScore score : v) {
                    if (rankScore.getKey().equals(score.getKey())) {
                        rankScore.setPriority(sets.stream().findFirst().get());
                        rankScore.setScore(rankScore.getScore() + 1);
                        sets.remove(rankScore.getPriority());
                    }
                }
            }
        });
    }


    /**
     * @param reqs 自动排班结果保存
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void automaticAdd(List<DispatchKeepWatchReq> reqs) {
        Set<Date> dutyList = reqs.stream().map(DispatchKeepWatchReq::getKeepWatchDate).collect(Collectors.toSet());
        //先添加值班人员
        try {
            for (Date s : dutyList) {
                DispatchKeepWatchReq req = reqs.stream().filter(o -> DateUtil.isSameDay(o.getKeepWatchDate(), s)).findFirst().get();
                DispatchKeepWatchDutyReq dutyReq = new DispatchKeepWatchDutyReq();
                BeanUtil.copyProperties(req, dutyReq);
                this.insertDuty(dutyReq);
            }
        } catch (Exception e) {
            if (e instanceof HuaNengException) {
                throw e;
            }
            log.error("值班人员自动排班失败", e);
            throw new HuaNengException(Constants.FAIL, "值班人员自动排班失败");
        }

        //再添加带班人员
        try {
            for (DispatchKeepWatchReq req : reqs) {
                DispatchKeepWatchLeadReq leadReq = new DispatchKeepWatchLeadReq();
                BeanUtil.copyProperties(req, leadReq);
                this.insertLead(leadReq);
            }
        } catch (Exception e) {
            if (e instanceof HuaNengException) {
                throw e;
            }
            log.error("带班人员自动排班失败", e);
            throw new HuaNengException(Constants.FAIL, "带班人员自动排班失败");
        }

    }

    @Override
    public List<DispatchKeepWatchVO> leadShiftList(String beginDate, String mineCode) {
        List<DispatchKeepWatchVO> list = dispatchKeepWatchMapper.leadShiftList(beginDate, "1", mineCode);
        return list;
    }

    @Override
    public DispatchKeepWatchVO getOnDutyPersonnel(String beginDate, String mineCode) {
        DispatchKeepWatchVO dispatchKeepWatchVO = new DispatchKeepWatchVO();
        //如果beginDate是空  ，则获取当前时间的带值班人员
        if (beginDate == null) {
            log.info(DateUtils.dateTimeNow());
            String s = DateUtils.dateTimeNow("HH:mm:ss");
            //查询班次信息

            DynamicDataSourceContextHolder.push("slave");
            List<DimShift> shiftList = dimShiftMapper.selectList(new LambdaQueryWrapper<DimShift>()
                    .eq(DimShift::getStatus, "0").eq(DimShift::getDelFlag, "0").orderByAsc(DimShift::getShiftStartTime));
            DynamicDataSourceContextHolder.clear();
            if (CollUtil.isEmpty(shiftList)) {
                throw new HuaNengException(Constants.FAIL, "班次信息不存在");
            }

            String shiftId = null;
            String shiftName = null;
            for (DimShift shift : shiftList) {
                String startTime = DateUtils.parseDateToStr("HH:mm:ss", shift.getShiftStartTime());
                String endTime = DateUtils.parseDateToStr("HH:mm:ss", shift.getShiftEndTime());
                if (isWithinTimePeriod(s, startTime, endTime)) {
                    System.out.println("当前时间段为" + shift.getShiftName());
                    shiftId = shift.getShiftId();
                    shiftName = shift.getShiftName();
                    break; // 找到匹配的班次后直接结束循环
                }
            }
            System.out.println(shiftId);
            //拿到班次后，根据当前年月日和班次查询班次表，type 1 是值班，2是带班。
            Date now = new Date();
            DispatchKeepWatch keepWatch = dispatchKeepWatchMapper.selectOne(new LambdaQueryWrapper<DispatchKeepWatch>()
                    .apply(" keep_watch_date = to_date('" + DateUtil.formatDate(now) + "','YYYY-MM-DD') ")
                    .eq(DispatchKeepWatch::getShiftId, shiftId)
                    .eq(DispatchKeepWatch::getType, "2")
                    .eq(DispatchKeepWatch::getDelFlag, "0")
                    .eq(DispatchKeepWatch::getMineCode, mineCode)
            );
            DispatchKeepWatchPerson dispatchKeepWatchPerson = null;
            if (keepWatch != null) {
                dispatchKeepWatchPerson = dispatchKeepWatchPersonMapper.selectById(keepWatch.getLeadPersonIds());
            }


            DispatchKeepWatch zhiban = dispatchKeepWatchMapper.selectOne(new LambdaQueryWrapper<DispatchKeepWatch>()
                    .apply(" keep_watch_date = to_date('" + DateUtil.formatDate(now) + "','YYYY-MM-DD') ")
                    .eq(DispatchKeepWatch::getType, "1")
                    .eq(DispatchKeepWatch::getDelFlag, "0")
                    .eq(DispatchKeepWatch::getMineCode, mineCode)
            );

            DispatchKeepWatchPerson zhibans = null;
            if (keepWatch != null) {
                zhibans = dispatchKeepWatchPersonMapper.selectById(zhiban.getDutyPersonIds());
            }

            dispatchKeepWatchVO.setShiftName(shiftName);
            dispatchKeepWatchVO.setShiftId(shiftId);

            dispatchKeepWatchVO.setLeadPersonNames(dispatchKeepWatchPerson.getKeepWatchPersonName());//带班人员名称
            dispatchKeepWatchVO.setDutyPersonNames(zhibans.getKeepWatchPersonName());//带班人员名称

        }
        return dispatchKeepWatchVO;
    }


    private static boolean isWithinTimePeriod(String currentTime, String startTime, String endTime) {
        return currentTime.compareTo(startTime) >= 0 && currentTime.compareTo(endTime) < 0;
    }

    @Override
    public List<DispatchKeepWatchVO> leadShiftListGty(String beginDate, String mineCode) {
        Calendar calendar = Calendar.getInstance();
        // 获取当前年
        int year = calendar.get(Calendar.YEAR);
        if (beginDate.equals(year + "")) {
            String sql = "update dispatch_keep_watch set keep_watch_date=to_timestamp('" + beginDate + "'||'-'||to_char(keep_watch_date,'mm')||'-'||to_char(keep_watch_date,'dd'),'YYYY-mm-dd')";
            dispatchKeepWatchMapper.daleteByDateGty(sql, mineCode);
        }
        List<DispatchKeepWatchVO> list = dispatchKeepWatchMapper.leadShiftList(beginDate, "2", mineCode);
        return list;
    }

    public List<DispatchKeepWatchVO> leadShiftListExport(String beginDate, String mineCode) {
        List<DispatchKeepWatchVO> list = dispatchKeepWatchMapper.leadShiftListExport(beginDate, mineCode);
        return list;
    }

    @Override
    public List<DispatchKeepWatchVO> dutyShiftList(String beginDate, String mineCode) {
        List<DispatchKeepWatchVO> list = dispatchKeepWatchMapper.dutyShiftList(beginDate, mineCode);
        return list;
    }

    @Override
    public List<DispatchKeepWatchVO> leadShiftStatistics(String beginDate, String mineCode) {
        List<DispatchKeepWatchVO> list = dispatchKeepWatchMapper.leadShiftStatistics(beginDate, mineCode);
        return list;
    }

    @Override
    public List<DispatchKeepWatchVO> dutyShiftStatistics(String beginDate, String mineCode) {
        List<DispatchKeepWatchVO> list = dispatchKeepWatchMapper.dutyShiftStatistics(beginDate, mineCode);
        return list;
    }

    private void createCell(HSSFWorkbook wb, HSSFRow row, int col, String val, HSSFColor.HSSFColorPredefined color) {
        row.setHeight((short) 400);
        HSSFCell cell = row.createCell(col);
        cell.setCellValue(val);
        HSSFCellStyle cellstyle = wb.createCellStyle();
        cellstyle.setAlignment(CENTER);// 设置水平对齐方式
        cellstyle.setVerticalAlignment(VerticalAlignment.CENTER);// 设置垂直对齐方式
        cell.setCellStyle(cellstyle);
//        cell.setCellStyle(getCellDefaultStyle(wb,HSSFColor.HSSFColorPredefined.WHITE.getIndex()));

    }

    private void createTitle(HSSFWorkbook wb, HSSFRow titleRow, String title) {
        titleRow.setHeight((short) 600);
        HSSFCell cell = titleRow.createCell(0);

        HSSFRichTextString h = new HSSFRichTextString(title);
        // 字体样式
        HSSFFont font = wb.createFont();
//        font.setColor((short) 8);
        font.setFontHeightInPoints((short) 18);
        font.setBold(true);
        h.applyFont(font);
        cell.setCellValue(h);
        cell.setCellStyle(getCellDefaultStyle(wb, HSSFColor.HSSFColorPredefined.WHITE.getIndex()));
    }

    private HSSFCellStyle getCellDefaultStyle(HSSFWorkbook wb, short color) {
        // 设置单元格样式
        HSSFCellStyle cellstyle = wb.createCellStyle();
        cellstyle.setAlignment(CENTER);// 设置水平对齐方式
        cellstyle.setVerticalAlignment(VerticalAlignment.CENTER);// 设置垂直对齐方式
        cellstyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
//        cellstyle.set
        cellstyle.setFillPattern(FillPatternType.forInt(1));
        cellstyle.setBorderBottom(THIN);
        cellstyle.setBorderLeft(THIN);
        cellstyle.setBorderRight(THIN);
        cellstyle.setBorderTop(THIN);
        cellstyle.setAlignment(CENTER);

        cellstyle.setWrapText(true);
        return cellstyle;
    }


    @Override
    public void exportLeadData(HttpServletResponse res, String beginDate, String mineCode) {
        List<DispatchKeepWatchVO> dispatchKeepWatchVOS = leadShiftListExport(beginDate, mineCode);
        if (CollUtil.isEmpty(dispatchKeepWatchVOS)) {
            throw new HuaNengException(Constants.FAIL, "数据为空，请先排班");
//            return "数据为空，请先排班";
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        sheet.autoSizeColumn(1, true);
        sheet.setVerticallyCenter(true);
//        sheet.setColumnWidth(0,256+184);
        wb.setSheetName(0, "带班表");
        HSSFRow titleRow = sheet.createRow(0);
        HSSFRow head = sheet.createRow(1);
        HSSFRow head2 = sheet.createRow(2);
        HSSFRow head3 = sheet.createRow(3);
        HSSFRow head4 = sheet.createRow(4);
        HSSFRow head21 = sheet.createRow(21);
        createTitle(wb, titleRow, "砚北煤矿" + beginDate + "月份管理人员下井带班表");
        createCell(wb, head, 0, "日期", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head2, 0, "班次", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head3, 0, "带班领导", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head4, 0, "带班成员", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 21));
        int rows = 1;
        int banciRows = 2;
        int renyuanRows = 3;
        int chengyuanRows = 4;
        int col = 1;
        int bancicol = 1;
        int s = 7;
        HSSFRow bodyRow = null;
        HSSFRow banci = null;
        HSSFRow renyuan = null;
        HSSFRow chengyuan = null;
        String banciName = "";
        String lingdaoName = "";

        for (int i = 0; i < dispatchKeepWatchVOS.size(); i++) {
            if (dispatchKeepWatchVOS.get(i).getKeepWatchDate() != null) {
                if (i != 0) {
                    col = col + 3;
                }
                if (i == s || i == s * 2 || i == s * 3 || i == s * 4 || i == s * 5) {
                    bodyRow = sheet.createRow(rows = rows + 4);
                    banci = sheet.createRow(banciRows = banciRows + 4);
                    renyuan = sheet.createRow(renyuanRows = renyuanRows + 4);
                    chengyuan = sheet.createRow(chengyuanRows = chengyuanRows + 4);
                    createCell(wb, bodyRow, 0, "日期", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    createCell(wb, banci, 0, "班次", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    createCell(wb, renyuan, 0, "带班领导", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    createCell(wb, chengyuan, 0, "带班成员", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    col = 1;
                    bancicol = 1;
                }
                createCell(wb, i < s ? head : bodyRow, col, DateUtils.dateTime(dispatchKeepWatchVOS.get(i).getKeepWatchDate()), HSSFColor.HSSFColorPredefined.AUTOMATIC);
                sheet.addMergedRegion(new CellRangeAddress(rows, rows, col, col + 2));
                for (int j = 1; j <= 3; j++) {
                    if (j == 3) {
                        banciName = "晚";
                        lingdaoName = dispatchKeepWatchVOS.get(i).getNightName();
                    } else if (j == 2) {
                        banciName = "中";
                        lingdaoName = dispatchKeepWatchVOS.get(i).getNoonName();
                    } else {
                        banciName = "早";
                        lingdaoName = dispatchKeepWatchVOS.get(i).getMorningName();
                    }
                    createCell(wb, i < s ? head2 : banci, bancicol, banciName, HSSFColor.HSSFColorPredefined.AUTOMATIC);
                    createCell(wb, i < s ? head3 : renyuan, bancicol, lingdaoName, HSSFColor.HSSFColorPredefined.AUTOMATIC);
                    bancicol++;
                }
            }

        }
        String requirement = "\t\t\t\t\t\t\t\t\t相关要求\t\t\t\t\t\n" +
                "1.严格执行《砚北煤矿领导带班下井工作制度（修订）》,矿领导为带班组长,根据矿井生产实际情况对重点工作及关键环节进行巡查\n" +
                "2.带班时间:早班6:00-14:00，中班14:00-21:00，夜班21:00-6:00 \n" +
                "3.带班人员必须按制度要求完成带班次数,因事不能下井带班时,委托同级别人员进行替班。\n" +
                "4.本表自2022年11月1日起执行。";
//        HSSFRow head17 = sheet.createRow(17);
//        HSSFRow head18 = sheet.createRow(18);
//        HSSFRow head19 = sheet.createRow(19);
//        HSSFRow head20 = sheet.createRow(20);
//        HSSFRow head21 = sheet.createRow(21);
        if (bodyRow == null || banci == null || renyuan == null || chengyuan == null) {
            bodyRow = sheet.createRow(17);
            banci = sheet.createRow(18);
            renyuan = sheet.createRow(19);
            chengyuan = sheet.createRow(20);
        }
        createCell(wb, bodyRow, dispatchKeepWatchVOS.size() == 30 ? 7 : 10, "\t\t\t\t\t\t\t相关要求\t\t\t\t\t\n", HSSFColor.HSSFColorPredefined.AUTOMATIC);
        createCell(wb, banci, dispatchKeepWatchVOS.size() == 30 ? 7 : 10, "1.严格执行《砚北煤矿领导带班下井工作制度（修订）》,矿领导为带班组长,根据矿井生产实际情况对重点工作及关键环节进行巡查", HSSFColor.HSSFColorPredefined.AUTOMATIC);
        createCell(wb, renyuan, dispatchKeepWatchVOS.size() == 30 ? 7 : 10, "2.带班时间:早班6:00-14:00，中班14:00-21:00，夜班21:00-6:00 ", HSSFColor.HSSFColorPredefined.AUTOMATIC);
        createCell(wb, chengyuan, dispatchKeepWatchVOS.size() == 30 ? 7 : 10, "3.带班人员必须按制度要求完成带班次数,因事不能下井带班时,委托同级别人员进行替班。", HSSFColor.HSSFColorPredefined.AUTOMATIC);
        createCell(wb, head21, dispatchKeepWatchVOS.size() == 30 ? 7 : 10, "4.本表自2022年11月1日起执行。", HSSFColor.HSSFColorPredefined.AUTOMATIC);
//        sheet.addMergedRegion(new CellRangeAddress(17,25,dispatchKeepWatchVOS.size()==30?7:10,21));

//        sheet.addMergedRegion(new CellRangeAddress(18,18,10,21));
//        sheet.addMergedRegion(new CellRangeAddress(19,19,10,21));
//        sheet.addMergedRegion(new CellRangeAddress(20,20,10,21));
        try {
            String fileName = URLEncoder.encode("砚北煤矿" + beginDate + "月份管理人员下井带班表", "UTF-8");
            res.setContentType("application/octet-stream;charset=UTF-8");
            res.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            OutputStream os = res.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
            wb.close();
        } catch (Exception e) {

        }
    }

    @Override
    public void exportDutyData(HttpServletResponse response, String beginDate) {
        List<DispatchKeepWatchVO> dutyList = dutyList(beginDate);
        if (CollUtil.isEmpty(dutyList)) {
            throw new HuaNengException(Constants.FAIL, "数据为空，请先排班");
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        sheet.setVerticallyCenter(true);
//        sheet.setColumnWidth(0,256+184);
        wb.setSheetName(0, "值班表");
        HSSFRow titleRow = sheet.createRow(0);
        HSSFRow head = sheet.createRow(1);
        HSSFRow head2 = sheet.createRow(2);
        createTitle(wb, titleRow, "砚北煤矿" + beginDate + "月份管理人员值班及冬季“四防”值班安排表");
        createCell(wb, head, 9, "签发:", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head2, 0, "序号", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head2, 1, "值班领导", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head2, 2, "值班成员", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head2, 7, "日期", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 2, 6));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 7, 10));
        int rows = 3;
        int col = 7;
        int colf = 7;
        int xuhao = 1;
        int rof = 0;
        HSSFRow bodyRow = null;
        HSSFRow bodyRow1 = null;
        for (DispatchKeepWatchVO dispatchKeepWatchVO : dutyList) {
            List<DispatchKeepWatchVO> dispatchKeepWatchVOS = allDutyList(beginDate, dispatchKeepWatchVO.getDutyPersonIds());
            bodyRow = sheet.createRow(rows);
            for (DispatchKeepWatchVO d : dispatchKeepWatchVOS) {
                if (rof == 0) {
                    createCell(wb, bodyRow, 0, String.valueOf(xuhao), HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    createCell(wb, bodyRow, 1, d.getDutyPersonNames(), HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    createCell(wb, bodyRow, col, DateUtils.dateTime(d.getKeepWatchDate()), HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    if (dispatchKeepWatchVOS.size() == 2) {
                        sheet.addMergedRegion(new CellRangeAddress(rows, rows, col, col + 1));
                    }
                } else if (rof == 1) {
                    if (dispatchKeepWatchVOS.size() == 2) {
                        sheet.addMergedRegion(new CellRangeAddress(rows, rows, col + 1, col + 2));
                    }
                    createCell(wb, bodyRow, dispatchKeepWatchVOS.size() == 2 ? col + 1 : col, DateUtils.dateTime(d.getKeepWatchDate()), HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                } else if (rof == 2) {
                    createCell(wb, bodyRow, col, DateUtils.dateTime(d.getKeepWatchDate()), HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                } else if (rof == 3) {
                    createCell(wb, bodyRow, col, DateUtils.dateTime(d.getKeepWatchDate()), HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                }
                rof++;
                col++;
            }
            rof = 0;
            col = 7;
            rows++;
            xuhao++;
        }
        bodyRow1 = sheet.createRow(rows + 1);
        HSSFRow bodyRow2 = sheet.createRow(rows + 2);
        HSSFRow bodyRow3 = sheet.createRow(rows + 3);
        HSSFRow bodyRow4 = sheet.createRow(rows + 4);
        HSSFRow bodyRow5 = sheet.createRow(rows + 5);
        HSSFRow bodyRow6 = sheet.createRow(rows + 6);
        createCell(wb, bodyRow1, 0, "备注", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, bodyRow1, 1, "1.矿值班执行24小时工作制。", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, bodyRow2, 1, "2.值班人员全面负责当天安全生产及其它事宜应急处置,随时抽查科室,区队值班情况", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, bodyRow3, 1, "3.矿值班人员必须参加当天安全生产调度会和集团公司口调度视频会,并至少参加两个区队(厂)班前会", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, bodyRow4, 1, "4.值班人员全面负责冬季“四防”隐忠排查及巡查工作，并做好巡查记示", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, bodyRow5, 1, "5.调度室、安检科、保卫科的值班工作自行安排，协同矿总值班履行职责", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, bodyRow6, 1, "6.本表自2022年11月1起执行", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        sheet.addMergedRegion(new CellRangeAddress(rows + 1, rows + 6, 0, 0));
        sheet.addMergedRegion(new CellRangeAddress(rows + 1, rows + 1, 1, 10));
        sheet.addMergedRegion(new CellRangeAddress(rows + 2, rows + 2, 1, 10));
        sheet.addMergedRegion(new CellRangeAddress(rows + 3, rows + 3, 1, 10));
        sheet.addMergedRegion(new CellRangeAddress(rows + 4, rows + 4, 1, 10));
        sheet.addMergedRegion(new CellRangeAddress(rows + 5, rows + 5, 1, 10));
        sheet.addMergedRegion(new CellRangeAddress(rows + 6, rows + 6, 1, 10));

        try {
            String fileName = URLEncoder.encode("砚北煤矿" + beginDate + "月份管理人员值班及冬季“四防”值班安排表", "UTF-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
            wb.close();
        } catch (Exception e) {

        }

    }

    @Override
    @Transactional
    public boolean updateDutyById(DispatchKeepWatchReq dispatchKeepWatch) {
        boolean conflict = true;
        //查询是否有带班
        QueryWrapper<DispatchKeepWatch> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("keep_watch_date", dispatchKeepWatch.getKeepWatchDate());
//        queryWrapper.eq("shift_id", dispatchKeepWatch.getShiftId());
        queryWrapper.eq("type", "2");
        queryWrapper.eq("lead_person_ids", dispatchKeepWatch.getDutyPersonIds());
        if (dispatchKeepWatchMapper.selectCount(queryWrapper) > 0) {
            conflict = false;
            return conflict;
//            throw new HuaNengException(Constants.FAIL, "与带班冲突,请调整带班!确定将置空该天值班人员");
        }
//        String[] result = dispatchKeepWatch.getLeadPersonIds().split(",");
//        for (String r : result) {
//            // r = 人员id
//
//        }
        //查询目标日得值班
        DispatchKeepWatch newKeepWatch = dispatchKeepWatchMapper.selectOne(new LambdaQueryWrapper<DispatchKeepWatch>()
                        .apply(" keep_watch_date = to_date('" + DateUtil.formatDate(dispatchKeepWatch.getKeepWatchDate()) + "','YYYY-MM-DD') ")
                        .eq(DispatchKeepWatch::getType, "1")
//                .eq(DispatchKeepWatch::getStatus, "0")
//                .eq(DispatchKeepWatch::getDelFlag,"0")
//                .last("and lead_person_ids='' limit 1")
        );
//        DispatchKeepWatch oldKeepWatch = dispatchKeepWatchMapper.selectOne(new LambdaQueryWrapper<DispatchKeepWatch>()
//                .apply(" keep_watch_date = to_date('" + DateUtil.formatDate(dispatchKeepWatch.getKeepWatchOldDate()) + "','YYYY-MM-DD') ")
//                .eq(DispatchKeepWatch::getStatus, "0")
//                .eq(DispatchKeepWatch::getDelFlag,"0")
//                .last("and lead_person_ids='' limit 1")
//        );
        int i = 0;
        int j = 0;
//        DispatchKeepWatch updateObj = dispatchKeepWatchMapper.selectOne();
        if (newKeepWatch == null) {
            //新增
            DispatchKeepWatch duty = new DispatchKeepWatch();
            duty.setKeepWatchDate(dispatchKeepWatch.getKeepWatchDate());
            duty.setDutyPersonIds(dispatchKeepWatch.getDutyPersonIds());
            duty.setLeadPersonIds("");
            duty.setStatus("0");
            duty.setType("1");
            duty.setDelFlag("0");
            dispatchKeepWatchMapper.insert(duty);
        } else {
            if (newKeepWatch.getDutyPersonIds().equals(dispatchKeepWatch.getDutyPersonIds())) {
                throw new HuaNengException(Constants.FAIL, "值班人员一致");
            }
            newKeepWatch.setDutyPersonIds(dispatchKeepWatch.getDutyPersonIds());
            i = dispatchKeepWatchMapper.updateById(newKeepWatch);
            if (i <= 0) {
                throw new HuaNengException(Constants.FAIL, "修改失败");
            }
        }
        return conflict;
    }

    @Override
    public boolean updateDutyByIdLD(UpdateDutyLDReq updateDutyLDReq) {
//        dutyPersonIds
        dispatchKeepWatchMapper.deleteDutyByDate(updateDutyLDReq.getKeepWatchDate());
        for (String dutyPersonId : updateDutyLDReq.getDutyPersonIds()) {
            // 处理每个dutyPersonId
            System.out.println(dutyPersonId);
            //新增
            DispatchKeepWatch duty = new DispatchKeepWatch();
            try {

                duty.setKeepWatchDate(DateUtils.parseDate(updateDutyLDReq.getKeepWatchDate(), "yyyy-MM-dd"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            duty.setDutyPersonIds(dutyPersonId);
            duty.setLeadPersonIds("");
            duty.setStatus("0");
            duty.setType("1");
            duty.setDelFlag("0");
            dispatchKeepWatchMapper.insert(duty);

        }


        return false;
    }

    @Override
    @Transactional
    public boolean updateLeadById(DispatchKeepWatchReq dispatchKeepWatch) {
        if (StrUtil.isBlank(dispatchKeepWatch.getLeadPersonIds())) {
            throw new HuaNengException(Constants.FAIL, "请选择带班人员");
        }
        if (StrUtil.isBlank(dispatchKeepWatch.getShiftId())) {
            throw new HuaNengException(Constants.FAIL, "请选择班次");
        }
        boolean conflict = true;
        //查询是否有值班
        String[] result = dispatchKeepWatch.getLeadPersonIds().split(",");
        List<DispatchKeepWatch> dispatchKeepWatches = new ArrayList<>();
        for (String r : result) {
            QueryWrapper<DispatchKeepWatch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("keep_watch_date", dispatchKeepWatch.getKeepWatchDate());
//        queryWrapper.eq("shift_id", dispatchKeepWatch.getShiftId());
            queryWrapper.eq("type", "1");
            queryWrapper.eq("duty_person_ids", r);
            dispatchKeepWatches.addAll(dispatchKeepWatchMapper.selectList(queryWrapper));
        }
        if (CollUtil.isNotEmpty(dispatchKeepWatches)) {
            conflict = false;
            return conflict;
        }
        //删除目标日得带班,新增某个班次得带班
        dispatchKeepWatchMapper.deleteByDate(DateUtil.formatDate(dispatchKeepWatch.getKeepWatchDate()), dispatchKeepWatch.getShiftId());
//        //删除原有班次人员
        String[] oldresult = dispatchKeepWatch.getLeadPersonIds().split(",");
        for (String r : oldresult) {
            dispatchKeepWatchMapper.deleteLeadByDate(DateUtil.formatDate(dispatchKeepWatch.getKeepWatchOldDate()), dispatchKeepWatch.getShiftId(), r);
        }
        for (String r : result) {
            DispatchKeepWatch dw = new DispatchKeepWatch();
            dw.setLeadPersonIds(r);
            dw.setType("2");
            dw.setDelFlag("0");
            dw.setStatus("0");
            dw.setShiftId(dispatchKeepWatch.getShiftId());
            dw.setKeepWatchDate(dispatchKeepWatch.getKeepWatchDate());
//            dw.setLeadPersonIds(r);
            dispatchKeepWatchMapper.insert(dw);
        }


        //查询目标日得带班
//        List<DispatchKeepWatch> newKeepWatch = dispatchKeepWatchMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatch>()
//                .apply(" keep_watch_date = to_date('" + DateUtil.formatDate(dispatchKeepWatch.getKeepWatchDate()) + "','YYYY-MM-DD') ")
//                .eq(DispatchKeepWatch::getStatus, "0")
//                .eq(DispatchKeepWatch::getType,"2")
//                .eq(DispatchKeepWatch::getDelFlag,"0")
//        );
//        if(CollUtil.isEmpty(newKeepWatch)){
//
//        }
        return conflict;


    }

    @Override
    public boolean updateLeadLDById(DispatchKeepWatchReq dispatchKeepWatch) {
        if (StrUtil.isBlank(dispatchKeepWatch.getLeadPersonIds())) {
            throw new HuaNengException(Constants.FAIL, "请选择带班人员");
        }
        if (StrUtil.isBlank(dispatchKeepWatch.getShiftId())) {
            throw new HuaNengException(Constants.FAIL, "请选择班次");
        }
        boolean conflict = true;
        //查询是否有值班
        String[] result = dispatchKeepWatch.getLeadPersonIds().split(",");

        //删除目标日得带班,新增某个班次得带班
        dispatchKeepWatchMapper.deleteByDate(DateUtil.formatDate(dispatchKeepWatch.getKeepWatchDate()), dispatchKeepWatch.getShiftId());
//        //删除原有班次人员
        String[] oldresult = dispatchKeepWatch.getLeadPersonOldIds().split(",");
        for (String r : oldresult) {
            dispatchKeepWatchMapper.deleteLeadByDate(DateUtil.formatDate(dispatchKeepWatch.getKeepWatchOldDate()), dispatchKeepWatch.getShiftId(), r);
        }
        dispatchKeepWatchMapper.deleteLeadByDateAll(DateUtil.formatDate(dispatchKeepWatch.getKeepWatchOldDate()), dispatchKeepWatch.getShiftId());

        for (String r : result) {
            DispatchKeepWatch dw = new DispatchKeepWatch();
            dw.setLeadPersonIds(r);
            dw.setType("2");
            dw.setDelFlag("0");
            dw.setStatus("0");
            dw.setShiftId(dispatchKeepWatch.getShiftId());
            dw.setKeepWatchDate(dispatchKeepWatch.getKeepWatchDate());
            dw.setMineCode(dispatchKeepWatch.getMineCode());
            dispatchKeepWatchMapper.insert(dw);
        }
        return conflict;
    }

    @Override
    public void emptyLead(DispatchKeepWatchReq dispatchKeepWatch) {
        //删除原有班次和原有日期人员
        dispatchKeepWatchMapper.deleteDutyByLead(DateUtil.formatDate(dispatchKeepWatch.getKeepWatchDate()), dispatchKeepWatch.getShiftId());
    }

    @Override
    public void emptyDuty(DispatchKeepWatchReq dispatchKeepWatch) {
        //删除原有日期人员
        dispatchKeepWatchMapper.deleteDutyByDate(DateUtil.formatDate(dispatchKeepWatch.getKeepWatchDate()));
    }

    @Override
    public void exportLeadDataGty(HttpServletResponse response, String beginDate, String mineCode) {
        List<DispatchKeepWatchVO> dispatchKeepWatchVOS = dispatchKeepWatchMapper.leadShiftListExportGty(beginDate, mineCode);
//        List<DispatchKeepWatchVO> dispatchKeepWatchVOS1  = dispatchKeepWatchMapper.leadShiftListExportGty(beginDate,"2");
        if (CollUtil.isEmpty(dispatchKeepWatchVOS)) {
            throw new HuaNengException(Constants.FAIL, "数据为空，请先排班");
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        sheet.autoSizeColumn(1, true);
        sheet.setVerticallyCenter(true);
//        sheet.setColumnWidth(0,256+184);
        wb.setSheetName(0, "带班表");
        HSSFRow titleRow = sheet.createRow(0);
        HSSFRow head = sheet.createRow(1);
        HSSFRow head2 = sheet.createRow(2);
        HSSFRow head3 = sheet.createRow(3);
        HSSFRow head4 = sheet.createRow(4);
//        HSSFRow head21 = sheet.createRow(21);
        createTitle(wb, titleRow, beginDate + "年高头窑煤矿管理人员带班安排表");
        createCell(wb, head, 0, "日期", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head2, 0, "班次", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head3, 0, "带班领导", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        createCell(wb, head4, 0, "带班成员", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 21));
        int rows = 1;
        int banciRows = 2;
        int renyuanRows = 3;
        int chengyuanRows = 4;
        int col = 1;
        int bancicol = 1;
        int s = 7;
        HSSFRow bodyRow = null;
        HSSFRow banci = null;
        HSSFRow renyuan = null;
        HSSFRow chengyuan = null;
        String banciName = "";
        String lingdaoName = "";
        String chengyuanName = "";

        for (int i = 0; i < dispatchKeepWatchVOS.size(); i++) {
            if (dispatchKeepWatchVOS.get(i).getDutyId() != null) {
                if (i != 0) {
                    col = col + 3;
                }
                if (i == s || i == s * 2 || i == s * 3 || i == s * 4 || i == s * 5) {
                    bodyRow = sheet.createRow(rows = rows + 4);
                    banci = sheet.createRow(banciRows = banciRows + 4);
                    renyuan = sheet.createRow(renyuanRows = renyuanRows + 4);
                    chengyuan = sheet.createRow(chengyuanRows = chengyuanRows + 4);
                    createCell(wb, bodyRow, 0, "日期", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    createCell(wb, banci, 0, "班次", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    createCell(wb, renyuan, 0, "带班领导", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    createCell(wb, chengyuan, 0, "带班成员", HSSFColor.HSSFColorPredefined.GREY_25_PERCENT);
                    col = 1;
                    bancicol = 1;
                }
                createCell(wb, i < s ? head : bodyRow, col, dispatchKeepWatchVOS.get(i).getDutyId(), HSSFColor.HSSFColorPredefined.AUTOMATIC);
                sheet.addMergedRegion(new CellRangeAddress(rows, rows, col, col + 2));
                for (int j = 1; j <= 3; j++) {
                    if (j == 3) {
                        banciName = "晚";
                        lingdaoName = dispatchKeepWatchVOS.get(i).getNightStaff();
                        chengyuanName = dispatchKeepWatchVOS.get(i).getNightName();
                    } else if (j == 2) {
                        banciName = "中";
                        lingdaoName = dispatchKeepWatchVOS.get(i).getNoonStaff();
                        chengyuanName = dispatchKeepWatchVOS.get(i).getNoonName();
                    } else {
                        banciName = "早";
                        lingdaoName = dispatchKeepWatchVOS.get(i).getMorningStaff();
                        chengyuanName = dispatchKeepWatchVOS.get(i).getMorningName();
                    }
                    createCell(wb, i < s ? head2 : banci, bancicol, banciName, HSSFColor.HSSFColorPredefined.AUTOMATIC);
                    createCell(wb, i < s ? head3 : renyuan, bancicol, lingdaoName, HSSFColor.HSSFColorPredefined.AUTOMATIC);
                    createCell(wb, i < s ? head4 : chengyuan, bancicol, chengyuanName, HSSFColor.HSSFColorPredefined.AUTOMATIC);
                    bancicol++;
                }
            }

        }
//        HSSFRow head17 = sheet.createRow(17);
//        HSSFRow head18 = sheet.createRow(18);
//        HSSFRow head19 = sheet.createRow(19);
//        HSSFRow head20 = sheet.createRow(20);
//        HSSFRow head21 = sheet.createRow(21);
        if (bodyRow == null || banci == null || renyuan == null || chengyuan == null) {
            bodyRow = sheet.createRow(17);
            banci = sheet.createRow(18);
            renyuan = sheet.createRow(19);
            chengyuan = sheet.createRow(20);
        }
        createCell(wb, bodyRow, dispatchKeepWatchVOS.size() == 30 ? 7 : 10, "\t\t\t\t\t\t\t注：\t\t\t\t\t\n", HSSFColor.HSSFColorPredefined.AUTOMATIC);
        createCell(wb, banci, dispatchKeepWatchVOS.size() == 30 ? 7 : 10, "1.带班领导按照规定的日期、班次带班、并填写好记录；", HSSFColor.HSSFColorPredefined.AUTOMATIC);
        createCell(wb, renyuan, dispatchKeepWatchVOS.size() == 30 ? 7 : 10, "2.若带班领导出差或请假时，自行安排替班，替班人员必须是带班表中的成员，并告知调度台；", HSSFColor.HSSFColorPredefined.AUTOMATIC);
        createCell(wb, chengyuan, dispatchKeepWatchVOS.size() == 30 ? 7 : 10, "3.本表自2023年1月1日执行，原带班安排表同事废止。", HSSFColor.HSSFColorPredefined.AUTOMATIC);
//        createCell(wb,head21,dispatchKeepWatchVOS.size()==30?7:10,"4.本表自2022年11月1日起执行。",HSSFColor.HSSFColorPredefined.AUTOMATIC);
//        sheet.addMergedRegion(new CellRangeAddress(17,25,dispatchKeepWatchVOS.size()==30?7:10,21));

//        sheet.addMergedRegion(new CellRangeAddress(18,18,10,21));
//        sheet.addMergedRegion(new CellRangeAddress(19,19,10,21));
//        sheet.addMergedRegion(new CellRangeAddress(20,20,10,21));
        try {
            String fileName = URLEncoder.encode("" + beginDate + "年高头窑煤矿管理人员带班安排表", "UTF-8");
//            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setContentType("application/vnd..ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
            wb.close();
        } catch (Exception e) {

        }
    }

    @Override
    public boolean updateLeadGtyById(DispatchKeepWatchReq dispatchKeepWatch) {
        if (StrUtil.isBlank(dispatchKeepWatch.getLeadPersonIds())) {
            throw new HuaNengException(Constants.FAIL, "请选择带班人员");
        }
        if (StrUtil.isBlank(dispatchKeepWatch.getShiftId())) {
            throw new HuaNengException(Constants.FAIL, "请选择班次");
        }
        boolean conflict = true;
        //查询是否有值班
        String[] result = dispatchKeepWatch.getLeadPersonIds().split(",");
        List<DispatchKeepWatch> dispatchKeepWatches = new ArrayList<>();
        for (String r : result) {
            QueryWrapper<DispatchKeepWatch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("keep_watch_date", dispatchKeepWatch.getKeepWatchDate());
//        queryWrapper.eq("shift_id", dispatchKeepWatch.getShiftId());
            queryWrapper.eq("type", "1");
            queryWrapper.eq("duty_person_ids", r);
            dispatchKeepWatches.addAll(dispatchKeepWatchMapper.selectList(queryWrapper));
        }
        if (CollUtil.isNotEmpty(dispatchKeepWatches)) {
            conflict = false;
            return conflict;
        }
        //删除目标日得带班,新增某个班次得带班
//        dispatchKeepWatchMapper.deleteByDate(DateUtil.formatDate(dispatchKeepWatch.getKeepWatchOldDate()),dispatchKeepWatch.getShiftId());
//        //删除原有班次人员
        String[] oldresult = dispatchKeepWatch.getLeadPersonOldIds().split(",");
        for (String r : oldresult) {
            dispatchKeepWatchMapper.deleteLeadByDate(DateUtil.formatDate(dispatchKeepWatch.getKeepWatchOldDate()), dispatchKeepWatch.getShiftoldId(), r);
        }
        String[] newresult = dispatchKeepWatch.getLeadPersonIds().split(",");
        for (String r : newresult) {
            DispatchKeepWatch dw = new DispatchKeepWatch();
            dw.setLeadPersonIds(r);
            dw.setType("2");
            dw.setDelFlag("0");
            dw.setStatus("0");
            dw.setShiftId(dispatchKeepWatch.getShiftId());
            dw.setKeepWatchDate(dispatchKeepWatch.getKeepWatchDate());
//            dw.setLeadPersonIds(r);
            dw.setMineCode(dispatchKeepWatch.getMineCode());
            dispatchKeepWatchMapper.insert(dw);
        }


        //查询目标日得带班
//        List<DispatchKeepWatch> newKeepWatch = dispatchKeepWatchMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatch>()
//                .apply(" keep_watch_date = to_date('" + DateUtil.formatDate(dispatchKeepWatch.getKeepWatchDate()) + "','YYYY-MM-DD') ")
//                .eq(DispatchKeepWatch::getStatus, "0")
//                .eq(DispatchKeepWatch::getType,"2")
//                .eq(DispatchKeepWatch::getDelFlag,"0")
//        );
//        if(CollUtil.isEmpty(newKeepWatch)){
//
//        }
        return conflict;
    }

    @Override
    public DispatchKeepWatchVO getOnDutyPersonnelOfLD(String beginDate, String mineCode) {
        DispatchKeepWatchVO dispatchKeepWatchVO = new DispatchKeepWatchVO();
        //如果beginDate是空  ，则获取当前时间的带值班人员
        if (beginDate == null) {
            System.out.println(DateUtils.dateTimeNow());
            String s = DateUtils.dateTimeNow("HH:mm:ss");
            //查询班次信息

            DynamicDataSourceContextHolder.push("slave");
            List<DimShift> shiftList = dimShiftMapper.selectList(new LambdaQueryWrapper<DimShift>()
                    .eq(DimShift::getStatus, "0").eq(DimShift::getDelFlag, "0").orderByAsc(DimShift::getShiftStartTime));
            DynamicDataSourceContextHolder.clear();
            if (CollUtil.isEmpty(shiftList)) {
                throw new HuaNengException(Constants.FAIL, "班次信息不存在");
            }

            String shiftId = null;
            String shiftName = null;
            for (DimShift shift : shiftList) {
                String startTime = DateUtils.parseDateToStr("HH:mm:ss", shift.getShiftStartTime());
                String endTime = DateUtils.parseDateToStr("HH:mm:ss", shift.getShiftEndTime());
                if (isWithinTimePeriod(s, startTime, endTime)) {
                    System.out.println("当前时间段为" + shift.getShiftName());
                    shiftId = shift.getShiftId();
                    shiftName = shift.getShiftName();
                    break; // 找到匹配的班次后直接结束循环
                }
            }
            System.out.println(shiftId);
            //拿到班次后，根据当前年月日和班次查询班次表，type 1 是值班，2是带班。
            Date now = new Date();
            List<DispatchKeepWatch> dispatchKeepWatches = dispatchKeepWatchMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatch>()
                    .apply(" keep_watch_date = to_date('" + DateUtil.formatDate(now) + "','YYYY-MM-DD') ")
                    .eq(DispatchKeepWatch::getShiftId, shiftId)
                    .eq(DispatchKeepWatch::getType, "2")
                    .eq(DispatchKeepWatch::getDelFlag, "0")
                    .eq(DispatchKeepWatch::getMineCode, mineCode)
            );

            List<DispatchKeepWatchPerson> dispatchKeepWatchPerson = new ArrayList<>();
            if (dispatchKeepWatches != null) {
                for (DispatchKeepWatch dispatchKeepWatch : dispatchKeepWatches) {
                    dispatchKeepWatchPerson.add(dispatchKeepWatchPersonMapper.selectById(dispatchKeepWatch.getLeadPersonIds()));
                }
            }


            List<DispatchKeepWatch> zhiban = dispatchKeepWatchMapper.selectList(new LambdaQueryWrapper<DispatchKeepWatch>()
                    .apply(" keep_watch_date = to_date('" + DateUtil.formatDate(now) + "','YYYY-MM-DD') ")
                    .eq(DispatchKeepWatch::getType, "1")
                    .eq(DispatchKeepWatch::getDelFlag, "0")
                    .eq(DispatchKeepWatch::getMineCode, mineCode)
            );

            List<DispatchKeepWatchPerson> zhibans = new ArrayList<>();
            if (zhiban != null) {
                for (DispatchKeepWatch dispatchKeepWatch : zhiban) {
                    zhibans.add(dispatchKeepWatchPersonMapper.selectById(dispatchKeepWatch.getDutyPersonIds()));

                }
            }

            dispatchKeepWatchVO.setShiftName(shiftName);
            dispatchKeepWatchVO.setShiftId(shiftId);
            String daiban = "";
            if (dispatchKeepWatchPerson != null) {
                daiban = dispatchKeepWatchPerson.stream()
                        .map(DispatchKeepWatchPerson::getKeepWatchPersonName)
                        .collect(Collectors.joining(","));
            }


            String zhibanren = "";
            if (zhibans != null) {
                zhibanren = zhibans.stream()
                        .map(DispatchKeepWatchPerson::getKeepWatchPersonName)
                        .collect(Collectors.joining(","));
            }
            dispatchKeepWatchVO.setLeadPersonNames(daiban);//带班人员名称
            dispatchKeepWatchVO.setDutyPersonNames(zhibanren);//带班人员名称

        }
        return dispatchKeepWatchVO;
    }

    @Override
    public void importResult(MultipartFile file, String mineCode) {
        String sufix = StrUtil.subAfter(file.getOriginalFilename(), ".", true);
        if (!"xls".equals(sufix) && !"xlsx".equals(sufix))
            throw new HuaNengException(Constants.FAIL, "文件格式仅支持xls或xlsx");

        try {
            ExcelResult<DispatchKeepWatchReq> excel = ExcelUtil.importExcel(file.getInputStream(), DispatchKeepWatchReq.class, 1);
            List<DispatchKeepWatchReq> entitiesFromExcel = excel.getList();
            if (CollUtil.isEmpty(entitiesFromExcel)) {
                if (CollUtil.isEmpty(excel.getErrorList())) {
                    throw new HuaNengException(Constants.FAIL, "文件未包含有效数据");
                }
                throw new HuaNengException(Constants.FAIL, excel.getErrorList().get(0));
            }
            //查询班次
            DynamicDataSourceContextHolder.push("slave");
            List<DimShift> shiftList = dimShiftMapper.selectList(new LambdaQueryWrapper<DimShift>()
                    .eq(DimShift::getStatus, "0").eq(DimShift::getDelFlag, "0").orderByAsc(DimShift::getShiftStartTime));
            DynamicDataSourceContextHolder.clear();
            //复制煤矿编码
            entitiesFromExcel.stream().distinct().forEach(item -> item.setMineCode(mineCode));

            List<DispatchKeepWatchPersonVO> watchPersons = dispatchKeepWatchPersonMapper.selectWatchPersonsByNames();
            Map<String, String> watchPersonMap = watchPersons.stream()
                    .collect(Collectors.toMap(
                            DispatchKeepWatchPersonVO::getKeepWatchPersonName,  // 键: 人员名称
                            DispatchKeepWatchPersonVO::getKeepWatchPersonId                   // 值: 人员 ID
                    ));
//                DispatchKeepWatchLeadReq dispatchKeepWatchLeadReq = new DispatchKeepWatchLeadReq();
//                insertLeadLD(dispatchKeepWatchLeadReq);


            List<DispatchKeepWatch> updatedList = new ArrayList<>();
            //错误信息
            List<String> missingPersonIds = new ArrayList<>();
            for (DispatchKeepWatchReq entity : entitiesFromExcel) {
                boolean found = false;
                String personId = watchPersonMap.get(entity.getFirstShiftPersonName1());
                String personName2 = watchPersonMap.get(entity.getFirstShiftPersonName2());
                String personName3 = watchPersonMap.get(entity.getSecondShiftPersonName1());
                String personName4 = watchPersonMap.get(entity.getSecondShiftPersonName2());
                String personName5 = watchPersonMap.get(entity.getThirdShiftPersonName1());
                String personName6 = watchPersonMap.get(entity.getThirdShiftPersonName2());
                String nightName = watchPersonMap.get(entity.getNightShiftPersonName());
                String dayName = watchPersonMap.get(entity.getDayShiftGroundPersonName());

                String type = "2";
                String shiftId = null;

                if (nightName != null) {
                    updatedList.add(createDispatchKeepWatch(nightName, "", "3", entity.getKeepWatchDate()));
                    found = true;
                }
                if (dayName != null) {
                    updatedList.add(createDispatchKeepWatch(dayName, "", "1", entity.getKeepWatchDate()));
                    found = true;
                }
                if (personId != null) {
                    shiftId = shiftList.get(0).getShiftId();
                    updatedList.add(createDispatchKeepWatch(personId, shiftId, type, entity.getKeepWatchDate()));
                    found = true;
                }
                if (personName2 != null) {
                    shiftId = shiftList.get(0).getShiftId();
                    updatedList.add(createDispatchKeepWatch(personName2, shiftId, type, entity.getKeepWatchDate()));
                    found = true;
                }
                if (personName3 != null) {
                    shiftId = shiftList.get(1).getShiftId();
                    updatedList.add(createDispatchKeepWatch(personName3, shiftId, type, entity.getKeepWatchDate()));
                    found = true;
                }
                if (personName4 != null) {
                    shiftId = shiftList.get(1).getShiftId();
                    updatedList.add(createDispatchKeepWatch(personName4, shiftId, type, entity.getKeepWatchDate()));
                    found = true;
                }
                if (personName5 != null) {
                    shiftId = shiftList.get(2).getShiftId();
                    updatedList.add(createDispatchKeepWatch(personName5, shiftId, type, entity.getKeepWatchDate()));
                    found = true;
                }
                if (personName6 != null) {
                    shiftId = shiftList.get(2).getShiftId();
                    updatedList.add(createDispatchKeepWatch(personName6, shiftId, type, entity.getKeepWatchDate()));
                    found = true;
                }

                if (!found) {
                    missingPersonIds.add(entity.getFirstShiftPersonName1());
                }
            }

            if (!missingPersonIds.isEmpty()) {
                throw new HuaNengException(Constants.FAIL, "未找到对应人员 ID: " + String.join(", ", missingPersonIds));
            }

            int batchSize = 1000;
            int count = (int) Math.ceil(updatedList.size() / (double) batchSize);
            for (int i = 0; i < count; i++) {
                dispatchKeepWatchMapper.insertBatch(CollUtil.sub(updatedList, i * batchSize, (i + 1) * batchSize));
            }
            RedisUtils.deleteObject(cacheKey);
        } catch (IOException e) {
            throw new HuaNengException(Constants.FAIL, "读取文件异常");
        }
    }

    private DispatchKeepWatch createDispatchKeepWatch(String leadPersonId, String shiftId, String type, Date keepWatchDate) {
        DispatchKeepWatch dispatchKeepWatch = new DispatchKeepWatch();
        if (leadPersonId != null) {
            if ("1".equals(type)) {
                dispatchKeepWatch.setDutyPersonIds(leadPersonId);
            } else if ("3".equals(type)) {
                dispatchKeepWatch.setDutyPersonIds(leadPersonId);
            } else {
                dispatchKeepWatch.setLeadPersonIds(leadPersonId);
            }
        }
        dispatchKeepWatch.setShiftId(shiftId);
        dispatchKeepWatch.setType(type);
        dispatchKeepWatch.setKeepWatchDate(keepWatchDate);
        return dispatchKeepWatch;
    }

    //查询要导出得值班人员
    public List<DispatchKeepWatchVO> dutyList(String beginDate) {
        List<DispatchKeepWatchVO> list = dispatchKeepWatchMapper.dutyList(beginDate);
        return list;
    }

    //查询所有值班人员
    public List<DispatchKeepWatchVO> allDutyList(String beginDate, String dutyPersonIds) {
        List<DispatchKeepWatchVO> list = dispatchKeepWatchMapper.allDutyList(beginDate, dutyPersonIds);
        return list;
    }
}
